4

I was trying to make my own function that will plot many plots side by side using ggplot and taking a list of dataframes as an argument. However, I run across this error, which as far as I have determined is related to do.call function and environment issues:

my_df<-data.frame(a=rnorm(25),b=runif(25))
my_list<-list(my_df,my_df*2)
reproducible_function<-function(a_list){
  dd<-list()
  for (i in 1:length(a_list)){
    p<-ggplot(data=a_list[[i]],aes(x=1:nrow(a_list[[i]]),y="something"))
    dd[[i]]<-p+geom_line(aes(y=a,colour="a"))+geom_line(aes(y=b,color="b"))
  }

  do.call(grid.arrange,dd)
}
reproducible_function(my_list)

however, I get the following error:

Error in nrow(a_list[[i]]) : object 'a_list' not found 

When not in a function, everything runs smoothly. But when I try to use a do.call function inside my own function something happens (I get same kind of errors when using eval(parse)).

Dominix
  • 935
  • 8
  • 14
  • 1
    See https://stackoverflow.com/questions/22287498/scoping-of-variables-in-aes-inside-a-function-in-ggplot. You can solve the problem by adding `p$plot_env <- environment();` immediately after you create `p` in the for-loop. – bgoldst Dec 27 '15 at 20:23
  • There is a similar solution at http://stackoverflow.com/questions/10659133/local-variables-within-aes. I tried this on your code and it worked. – steveb Dec 27 '15 at 20:31
  • Adding p$plot_env <- environment() solved the problem, thanks a lot! – Dominix Dec 27 '15 at 20:50
  • A workaround would be to add the `x` variable to the data frame: `a_list[[i]]$x <- 1:nrow(a_list[[i]])` and then use `aes(x = x, y = "something")`. Also see: https://github.com/hadley/ggplot2/issues/743 – G. Grothendieck Dec 27 '15 at 23:51

1 Answers1

2

Just add this line right after you create p inside loop:

p$plot_env <- environment()
Mirek Długosz
  • 4,205
  • 3
  • 24
  • 41