How can I keep saving figures to a pdf with R. Consider the following example:
require(ggplot2)
require(gridExtra)
TopFolder <- "...directory on my drive"
setwd(TopFolder)
pdf(file = paste(TopFolder,"figures","example.pdf",sep = "\\"))
g <- list()
for(i in 1:4){
dat <- data.frame(d1 = c(1:10),
d2 = runif(10))
g[[i]] <- qplot(x = d1, y = d2,
data = dat)
}
grid.arrange(g[[1]],g[[2]],g[[3]],g[[4]])
for(i in 1:6){
dat <- data.frame(d1 = c(1:20),
d2 = runif(20))
qplot(x = d1, y = d2,
data = dat)
}
dev.off()
My question is: Why doesn't the sesond set of plots i.e. the 6 generated by the second for loop show up in the pdf file? The only obvious difference I can spot is that I store the plots in the first loop and do't in the second. Why doesn't R generate these plots in the second loop and save them in the pdf after completion?
The result I would expect from this example would be to have the first page of the pdf with the four subplots and then have 6 pages following with one figure in each page. Why isn't this being generated? I would have thought that R would keep generating the figures in the file until dev.off() was called?