How to pass / evaluate function arguments within another function for use with ggplot?

蓝咒 提交于 2019-12-01 03:52:49

问题


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.


回答1:


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()
}


来源:https://stackoverflow.com/questions/7793306/how-to-pass-evaluate-function-arguments-within-another-function-for-use-with-g

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!