Overview

You don’t necessary need to author an R Markdown document to create a dynamic report. In fact, you can take any R script and compile it into a report that includes commentary, source code, and script output. Reports can be compiled to any output format including HTML, PDF, MS Word, and Markdown.

To compile a report from an R script you simply pass the script to render. For example:

rmarkdown::render("analysis.R")
rmarkdown::render("analysis.R", "pdf_document")

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

Metadata

By default the name of the script, username, and current date and time are included in the header of the report You can override this default behavior by including metadata in a specially formatted R comment:

#' ---
#' title: "Crop Analysis Q3 2013"
#' author: "John Smith"
#' date: "May 3rd, 2014"
#' ---

You can also specify the output format within the metadata, for example:

#' ---
#' title: "Crop Analysis Q3 2013"
#' output: pdf_document
#' ---

Markdown Formatting

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 compiled report For example:

#' A script comment that includes **markdown** formatting.

Rather than displaying as an R comment in the compiled report any roxygen2 style comment will be treated as markdown and rendered accordingly.

knitr Spin

Including markdown within R comments is possible because rmarkdown::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 (#+). For example:

#+ fig.width=5, fig.height=5
plot(cars)

For more information on using spin see:

Note that when using rmarkdown::render the spin function is called automatically under the hood as part of rendering.