1

If I want to create a list of ggplot objects, then every new plot overwrites the old plot. It is similar to what was asked here. Though I was able to solve the issue using lapply, but I am still not able to figure out why the plots are getting overwritten inside the loop.

library(ggplot2)
trash <- data.frame(matrix(rnorm(100), nrow = 50, ncol = 2))
colTrash <- data.frame(matrix(rnorm(100), nrow = 50, ncol = 2))

##Overwritten: both plots are same
pltList <- list()
for(i in 1:2){
  pltList[[i]] <- ggplot(trash)+
    geom_point(aes(X1,X2,color = colTrash[,i]))
}

#Not Overwritten: plots are different and correct
pltList <- lapply(1:2, function(i){
  ggplot(trash)+
    geom_point(aes(X1,X2,color = colTrash[,i]))
})
Manish Goel
  • 843
  • 1
  • 8
  • 21
  • 2
    You encountered lazy evaluation! In the loop only the call to the function is stored, it is not evaluated. Evaluation happens when you try to display the plot. To illustrate this first run your loop and then set `i<-NULL` - now none of the plots can be evaluated! – wici Oct 06 '17 at 22:25
  • So does that mean that in case the case of `lapply` evaluation occurs instantaneously? Also, what is the specific use of lazy evaluation? – Manish Goel Oct 06 '17 at 22:33
  • 1
    [Here](https://stackoverflow.com/questions/26235825/for-loop-only-adds-the-final-ggplot-layer), [here](https://stackoverflow.com/questions/44317502/update-a-ggplot-using-a-for-loop-r?noredirect=1&lq=1), and [here](https://stackoverflow.com/questions/39057189/strange-behaviour-of-ggplot2/39057372#39057372) are a few SO questions that address this issue. Lazy evaluation is discussed [here](http://adv-r.had.co.nz/Functions.html) in the book Advanced R. – eipi10 Oct 06 '17 at 22:57
  • If you use `force` inside your loop (appropriately) you can force it to evaluate and things will run as you expect. – Dason Oct 06 '17 at 22:59

0 Answers0