5

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.

Community
  • 1
  • 1
Matt Bannert
  • 27,631
  • 38
  • 141
  • 207

1 Answers1

9

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()
}
kohske
  • 65,572
  • 8
  • 165
  • 155
  • Thanks koshke, I wish I wouldn't miss so many tiny tricks all the time. Yet it helps a bit to understand how ggplot was written. – Matt Bannert Oct 17 '11 at 12:22