Can Sweave produce many pdfs automatically?

You can use something like a for loop with a global variable changing, which controls which city you want to weave into the report; see the other post Run Sweave or knitr with objects from existing R session

The code will be like (suppose cities is a character vector, and I use the knitr package as an example because you can specify the filename of the output):

for (city in cities) {
   knit('city_template.Rnw', output = paste('report_', city, '.tex', sep = ''))
}

Inside city_template.Rnw, you have a chunk like

<<do-my-job>>=
make_plot(city, ...)
whatever(city, ...)
@

Then you will get a series of tex files named by the cities, and the rest of your job is to compile them to PDF (not possible for RStudio to compile multiple tex files, AFAIK, but it is trivial to do it in command line or in R with texi2dvi()).

There is one thing you need to be careful — you have to use a different figure prefix (the option fig.path) for each output file, otherwise different cities can override each other’s figure output. In knitr, this can be done by like this:

<<setup, echo=FALSE>>=
opts_chunk$set(fig.path = paste('my-prefix-', city, sep = ''))
@

I believe this should be safe to produce many reports with a loop.

BTW, you can certainly achieve the same goal with Sweave; perhaps you will know why I developed knitr later (this is off-topic, so I won’t expand here).

Leave a Comment