I would like to accomplish the following in R: I one same for loop, I would like to save different plots to different jpeg files. My problem is that i don't know exactly how to tell R "save this plot in this open jpeg file and this other plot in this different jpeg file".
I can currently do this using two for loops:
library(data.table)
set.seed(10)
data1 <- data.table(A = letters[3:5], B = letters[6:8],
C = rnorm(20), D = rnorm (20) )
for( i in unique(data1$A )){
data2 <- data1[A == i]
jpeg(paste(i,'plot1.jpg',sep = ''))
hist(data2$C)
dev.off()
}
for( i in unique(data1$A )){
data2 <- data1[A == i]
jpeg(paste(i,'plot2.jpg',sep = ''))
hist(data2$D)
dev.off()
}
However, I would like combine these two loops in a single one (what follows is not an actual code, but the idea of what I would like to accomplish):
for( i in unique(data1$A )){
data2 <- data1[A == i]
a <- jpeg(paste(i,'plot2.jpg',sep = ''))
b <- jpeg(paste(i,'plot2.jpg',sep = ''))
hist(data2$D, PLOT in a)
hist(data2$D, PLOT in b)
dev.off(CLOSE a AND b)
}
jpeg(paste0(i,'plot1.jpg')); hist(data2$C); dev.off();followed byjpeg(paste0(i,'plot2.jpg')); hist(data2$D); dev.off();within theforloop.