Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

eval

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.

like image 877
Matt Bannert Avatar asked Oct 17 '11 11:10

Matt Bannert


1 Answers

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()
}
like image 181
kohske Avatar answered Oct 07 '22 19:10

kohske