2

Running the R script

list1<-list()
list2<-list()

for(i in 1:3){
  list1[[i]]<-i
}

for(i in 1:3){
  list2[[i]]<-qplot(i)
}

I recognize that list1 contains the elements 1,2,3. But list2 contains three times the element qplot(3).

Is qplot not compatible with looping? How can I save my plots in a list using a loop?

1
  • @David Arenburg: Mh, my problem is not printing, but saving. For me, the code from the question you pointed to, already prints 3 different graphs in RStudio - without adding dev.new()... Commented Apr 6, 2014 at 17:29

1 Answer 1

3

In ggplot the aesthetics are stored as expressions and evaluated when the plot is rendered. So qplot(i) does not generate a plot, but rather a plot definition, using a reference to the variable i. All three plots are the same in the sense that they all reference i.

If you type

list2[[1]]

after the second loop has run, you cause the ggplot object stored in list2[[1]] to be rendered, using whatever value i is set to at the moment (which is 3 after the loop).

Try this:

i <- 4
list2[[1]]

Now the plot rendered is equivalent to qplot(4).

The workaround depends on what you are trying to achieve. The basic idea is not to use external variables in aesthetics. So in your trivial case,

for(i in 1:3){
  list2[[i]]<-ggplot(data.frame(x=i), aes(x))+geom_histogram()
}

will work. This is because the reference to the external variable i is not in the aesthetics (e.g., the call to aes(...).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. The difference in handling the dataframe and the aesthetics still seems a bit counter-intuitive. But keeping that in mind I can at least create lists of plots for variable dataframes, which already solves my problem.
It's completely counter-intuitive, hopelessly abstruse, and utterly infuriating. What's worse, since qplot(...) is a wrapper for the more complex ggplot(...) calls, you don't really know when it's using aes(...) and when not. My advice is: 1 - give up on qplot(...) and just learn ggplot, and 2 - try to avoid putting any external references into the calls to aes(...).

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.