Quick reporting

Build a report based on an R script

2012-01-26

Sometimes we just want to run the code in an R script to create a report. Indeed you can paste the code in an R console, and copy the results. This is often very messy (code mangled with results), and most importantly, you lose the graphics output.

stitch(): feed a template with an R script

Knitr introduced a function stitch() to conveniently insert an R script into a template to create a simple report, preserving everything in the R output (either text results or plots). See ?stitch for details.

There are a LaTeX template, an HTML template and a markdown template in knitr. The first one can produce a PDF document, and the second can produce an HTML page. My motivation with this function is to make it easier for students to turn their R scripts into reports (e.g. homework) quickly. The traditional way is usually they run code in R, do the tedious job of collecting results line by line, copy and paste them into (ugly-looking) MS Word. With this function, they can either turn in the PDF document, publish the HTML pages on the web, or share the HTML page in some other way.

The usage is simple: just provide the path of the R script as the first argument to stitch(). It uses the LaTeX template by default.

spin(): comment out texts

The other way to write a quick report based on a pure R script is to use spin(). The R script needs to follow the rules below:

In this way, anything that is not R code is commented out.

#' Some texts here.

#+ test, echo=TRUE
rnorm(5)

This will be converted to a literate programming document, e.g. (depending on the output format)

Some texts here.

<<test, echo=TRUE>>=
rnorm(5)
@

See knitr-spin.R for a full example (knitr-spin.Rmd is the Rmd output, and you can make other formats like Rnw, RHTML and Rrst, etc).

library(knitr)
(s = system.file("examples", "knitr-spin.R", package = "knitr"))
spin(s)  # default markdown
o = spin(s, knit = FALSE)  # convert to Rmd only
knit2html(o)  # compile to HTML

# other formats
spin(s, FALSE, format = "Rnw")  # you need to write documentclass after #'
spin(s, FALSE, format = "Rhtml")
spin(s, FALSE, format = "Rtex")
spin(s, FALSE, format = "Rrst")