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:
- texts in roxygen comments
#'are preserved as normal texts (may contain inline R code);
- chunk options are written after
#+ chunk-label, opt1=value1, opt2=value2
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) @