I'm pretty new to knitr
, but I've written a script that generates a report for a county. One of the first lines in the first code chunk is display_county <- "King"
, and it queries a database to make all sorts of nice things about King County. Now I want to create reports for every county in my state. The only line in the script that needs be changed is the definition of display_county
.
I know the brew
packages is set up for stuff like this, and I know there's overlap between brew
and knitr
, but I don't know what I should be using.
This answer using Brew and Sweave would work with minor modifications, but is there a nice knitr
way to bypass brew
?
To create an R Markdown report, open a plain text file and save it with the extension . Rmd. You can open a plain text file in your scripts editor by clicking File > New File > Text File in the RStudio toolbar. Be sure to save the file with the extension .
knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.
Reports can be compiled to any output format including HTML, PDF, MS Word, and Markdown. The first call to render creates an HTML document, whereas the second creates a PDF document. If you are using RStudio then you can also create a report using the Compile Report command (Ctrl+Shift+K).
You can “knit” (produce) an R Markdown report in a variety of document formats (including HTML, PDF, MS Word, MS PowerPoint, and more) for easy sharing.
If I understand correctly, you are going to use the same Rnw file for each county, so only the variable display_county
will be different for each county. I would first make the call to the database to get all the names of counties and store them in a vector (say... myCounties
). After that, your reports can be generated with a script containing the following:
for(dc in myCounties) {
knit2pdf(input='county_report.Rnw', output=paste0(dc, '_county_report.pdf'))
}
To handle errors more effectively, you can also wrap the knit2pdf call on a tryCatch statement:
for(dc in myCounties) {
tryCatch(knit2pdf(input='county_report.Rnw', output=paste0(dc, '_county_report.pdf')))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With