0

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)

}
1
  • 1
    maybe jpeg(paste0(i,'plot1.jpg')); hist(data2$C); dev.off(); followed by jpeg(paste0(i,'plot2.jpg')); hist(data2$D); dev.off(); within the for loop. Commented Jan 19, 2017 at 17:57

1 Answer 1

2
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()

  jpeg(paste(i,'plot2.jpg',sep = ''))

  hist(data2$D)

  dev.off()

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

Comments

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.