2

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]))
})
4
  • 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! Commented Oct 6, 2017 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? Commented Oct 6, 2017 at 22:33
  • 2
    Here, here, and here are a few SO questions that address this issue. Lazy evaluation is discussed here in the book Advanced R. Commented Oct 6, 2017 at 22:57
  • If you use force inside your loop (appropriately) you can force it to evaluate and things will run as you expect. Commented Oct 6, 2017 at 22:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.