title: save plots to different jpeg files in a for loop in R
body: <p>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 <em>other</em> plot in this <em>different</em> jpeg file".</p>
  
  <p>I can currently do this using two for loops:</p>
  
  <pre><code>library(data.table)
  
  set.seed(10)
  
  data1 &lt;- data.table(A = letters[3:5], B = letters[6:8], 
                      C = rnorm(20), D = rnorm (20) )
  
  for( i in unique(data1$A )){
  
    data2 &lt;- data1[A == i]
  
    jpeg(paste(i,'plot1.jpg',sep = ''))
  
    hist(data2$C)
  
    dev.off()
  
  }
  
  for( i in unique(data1$A )){
  
    data2 &lt;- data1[A == i]
  
    jpeg(paste(i,'plot2.jpg',sep = ''))
  
    hist(data2$D)
  
    dev.off()
  
  }
  </code></pre>
  
  <p>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):</p>
  
  <pre><code>for( i in unique(data1$A )){
  
    data2 &lt;- data1[A == i]
  
    a &lt;- jpeg(paste(i,'plot2.jpg',sep = ''))
    b &lt;- jpeg(paste(i,'plot2.jpg',sep = ''))
  
    hist(data2$D, PLOT in a)
    hist(data2$D, PLOT in b)
  
    dev.off(CLOSE a AND b)
  
  }
  </code></pre>