Do.call in function - object not found error

I tried to create my own function that will build many sections side by side using ggplot and taking a list of dataframes as an argument. However, I encounter this error, which, as far as I have defined, is related to the do.call functions and the environment:

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 the function does not work, everything works smoothly. But when I try to use the do.call function inside my own function, something happens (I get the same errors when using eval (parse)).

+4
source share
1 answer

Just add this line immediately after creation inside the loop p:

p$plot_env <- environment()
+2

Source: https://habr.com/ru/post/1621898/


All Articles