How to pass / evaluate function arguments within a

2019-02-17 14:21发布

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 ggplot2
1条回答
再贱就再见
2楼-- · 2019-02-17 14:30

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

test <- function(x,n){
  graph <- ggplot(x, aes_string(x = names(x)[n]))
  graph + geom_bar()
}
查看更多
登录 后发表回答