如何在另一个函数中传递/评估函数参数,以便与ggplot一起使用?

时间:2022-04-27 18:02:23

Please consider the following code:

请考虑以下代码:

test <- function(x,n){

selection<-names(x)[n]
graph <- ggplot(x, aes(factor(selection)))
graph + geom_bar()
}

test(mtcars,1)

It throws an error cause R can't find selection. I also played around with substitute, eval and get without success. I found this similar question and thought I understood Joris' answer but can't use the same trick for arguments of ggplot as well.

它抛出一个错误,因为R找不到选择。我也用替代品,eval和get而不是成功。我发现了这个类似的问题,我想我理解了Joris的答案,但也不能用同样的技巧来解释ggplot的论点。

1 个解决方案

#1


9  

you can use aes_string for this purpose. So test should be like this:

您可以为此目的使用aes_string。所以测试应该是这样的:

test <- function(x,n){
  graph <- ggplot(x, aes_string(x = names(x)[n]))
  graph + geom_bar()
}

#1


9  

you can use aes_string for this purpose. So test should be like this:

您可以为此目的使用aes_string。所以测试应该是这样的:

test <- function(x,n){
  graph <- ggplot(x, aes_string(x = names(x)[n]))
  graph + geom_bar()
}