R knitr Markdown: Output Plots within For Loop

bnjmn picture bnjmn · Aug 14, 2012 · Viewed 25.8k times · Source

I would like to create an automated knitr report that will produce histograms for each numeric field within my dataframe. My goal is to do this without having to specify the actual fields (this dataset contains over 70 and I would also like to reuse the script).

I've tried a few different approaches:

  • saving the plot to an object, p, and then calling p after the loop
    • This only plots the final plot
  • Creating an array of plots, PLOTS <- NULL, and appending the plots within the loop PLOTS <- append(PLOTS, p)
    • Accessing these plots out of the loop did not work at all
  • Even tried saving each to a .png file but would rather not have to deal with the overhead of saving and then re-accessing each file

I'm afraid the intricacies of the plot devices are escaping me.

Question

How can I make the following chunk output each plot within the loop to the report? Currently, the best I can achieve is output of the final plot produced by saving it to an object and calling that object outside of the loop.

R markdown chunk using knitr in RStudio:

```{r plotNumeric, echo=TRUE, fig.height=3}
suppressPackageStartupMessages(library(ggplot2))
FIELDS <- names(df)[sapply(df, class)=="numeric"]
for (field in  FIELDS){
  qplot(df[,field], main=field)  
}
```

From this point, I hope to customize the plots further.

Answer

cbeleites unhappy with SX picture cbeleites unhappy with SX · Aug 15, 2012

Wrap the qplot in print.

knitr will do that for you if the qplot is outside a loop, but (at least the version I have installed) doesn't detect this inside the loop (which is consistent with the behaviour of the R command line).