After much editing and several useful comments...
I would like to loop through four files and plot the data in each one in four different plots, on the same page. I need to do this for every value of laneCombination
, which are column numbers. Using the code below (minimal example of the error), I get the desired result except that the plots contain the same data.
library(ggplot2)
library(grid)
library(gridExtra)
plots <- list()
for (laneCombination in 3:3) {
for (depVar in 1:4) {
simdata <- data.frame(cond = rep(c("A", "B"), each=10),
xvar = 1:20,
yvar = 1:20 + rnorm(20,sd=3))
plots[[depVar]] <- ggplot(simdata, aes(xvar, simdata[,laneCombination]), environment = environment()) +
geom_point() + geom_line() + labs(x="Duration", y=depVar) + theme(legend.position="none")
}
grid.arrange(plots[[1]], plots[[2]], plots[[3]], plots[[4]], ncol = 1, main = colnames(simdata[laneCombination]))
}
First three plots are overwritten with the last:
@eipi10 has correctly identified the problem in the comments: simdata[,laneCombination]
causes scope issues. However, the solution in the SO question referenced in his/her comment (Addressing x and y in aes by variable number) does not seem to solve the problem. I need to loop through the column numbers for my task.