[[base R]] Have two graphic devices open at the same time, and flip between the two

Viewed 43

I have a double for loop, as such:

for (alphabet in c("A","B")) {
   for (number in c(1,6)) {
      plot(......)
   }
}

What I wish to do is to have the total of 12 plots arranged in such a way that in the end there are two pngs exported, each one containing {{A1~3,B1~3}} and {{A4~6,B4~6}} respectively.

I'm not sure where the call to png() should be to achieve this.

My lab insists that I use base R only..

Thank you.

1 Answers

1) Do the first set and then the second set.

png("first.png")
par(mfcol = 3:2)
for (a in c("A","B")) for(n in 1:3) plot(0, main = paste(a, n))
dev.off()

png("second.png")
par(mfcol = 3:2)
for (a in c("A","B")) for(n in 4:6) plot(0, main = paste(a, n))
dev.off()

Here is first.png. second.png is similar.

screenshot

2) Although (1) seems simpler if you really want to switch back and forth then:

png("first.png")
first <- dev.cur()
par(mfcol = 3:2)

png("second.png")
second <- dev.cur()
par(mfcol = 3:2)

for (a in c("A","B")) {
   for (n in 1:6) {
     dev.set(if (n <= 3) first else second)
     plot(0, main = paste(a, n))
   }
}

dev.off(first)
dev.off(second)
Related