R Markdown can also compile R scripts to a notebook which includes commentary, source code, and script output. Notebooks can be compiled to any output format including HTML, PDF, and MS Word.
To compile a notebook from an R script you simply pass the script to
render
. For example:
The first call to render
creates an HTML document, whereas
the second creates a PDF document.
By default the name of the script, username, and current date and time are included in the header of the generated notebook. You can override this default behavior by including explicit metadata in a specially formatted R comment:
#' ---
#' title: "Crop Analysis Q3 2013"
#' author: "John Smith"
#' date: "May 3rd, 2014"
#' ---
Note that the R comment used above to add a title, author, and date includes a single-quote as a special prefix character. This is a roxygen2 style comment, and it's actually possible to include many such comments in an R script, all of which will be converted to markdown content within the generated notebook. For example:
#' A script comment that includes **markdown** formatting.
Rather than displaying as an R comment in the compiled notebook any roxygen2 style comment will be treated as markdown and rendered accordingly.
Including markdown within R comments is possible because render
calls the knitr spin
function to convert the R
script to an Rmd file. The spin
function also enables you to add
knitr
chunk options with another special comment prefix (#+
).
Here's an example of a script that uses the various features of spin
:
https://github.com/yihui/knitr/blob/master/inst/examples/knitr-spin.R
For more details on knitr::spin
see the following documentation: