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
  • 875
  • 8
  • 14

1 Answers1

2

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

p$plot_env <- environment()
Mirek Długosz
  • 4,035
  • 3
  • 23
  • 40