title: subsetting a df by group, looping through scatter plots
body: <p>I'd like to automate generation of a few hundred scatter plots, but I'm not having much success with a compact way to handle the subsetting.  The data frame has three fields of interest:</p>
  
  <pre><code>site           code            value
  
  1              x                30
  1              y                14
  1              z                12
  2              x                35
  2              y                19
  </code></pre>
  
  <p>etc, </p>
  
  <p>where site= numeric, value = numeric, code = grouping variable.</p>
  
  <p>There are about 400 sites and 300 codes. </p>
  
  <p>What I want:</p>
  
  <ol>
  <li>subset the df based on field =code</li>
  <li>plot x=site vs y=value, as scatter plot</li>
  <li>write each scatterplot to a separate page in a .pdf</li>
  <li>automate the process</li>
  </ol>
  
  <p>Any comments are appreciated. This approach, for example, generates the error  'subset' must evaluate to logical.  The lapply call may not work either.</p>
  
  <pre><code>dfarray&lt;-list(subset(df,df[,2]))
  pdf(file="test.pdf")
  figures&lt;-lapply(dfarray, function(i) {(plot(i$[,1],i$[,3]))
  })
  dev.off()
  </code></pre>
  
  <p>Thanks much</p>
  
  <p>Incorporating d_ply worked great.  I'm happy with this result, but can anyone point out what's amiss with the label statement for the X,Y axes? (Note: this code block results in 1 pdf per subset)</p>
  
  <pre><code>names(df)&lt;-tolower(names(df))
  names(df)
  d_ply(df,"code",function(x){
  pdf(file=paste(unique(x$code),".pdf"))
  plot(data=x,value~site, xlab=names(x[1]),ylab=as.name(x$code))
  dev.off()
  })
  </code></pre>
  
  <p>Update:  Below are two functioning versions of this code, assuming the dataframe df exists.  This one writes a scatterplot of each group to a separate .pdf:</p>
  
  <pre><code>names(df)&lt;-tolower(names(df)
  names(df)
  d_ply(df,"code",function(x){
  pdf(file=paste(unique(x$code),".pdf"))
  plot(data=x, value~site, xlab=names(df[1]),ylab=unique(x$code))
  dev.off()
  })
  </code></pre>
  
  <p>This one writes all scatterplots, one per group, to a single .pdf:</p>
  
  <pre><code>names(df)&lt;-tolower(names(df)
  names(df)
  pdf(file="df_all.pdf")
  d_ply( df, "code", function(x) {
  plot(data=x, value~site, xlab=names(df[1]), ylab=unique(x$code))
  })
  dev.off()
  </code></pre>