Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating knitr reports

Tags:

r

knitr

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?

like image 304
Gregor Thomas Avatar asked Mar 08 '13 23:03

Gregor Thomas


People also ask

How do I create a Markdown report?

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 .

What is a knitr document?

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.

How do I create a report in RStudio?

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).

What tool can help them create this shareable report in R?

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.


1 Answers

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')))
}
like image 197
JAponte Avatar answered Dec 24 '22 01:12

JAponte