15.5 R package vignettes

If you have experience in developing R packages, or your project requires clear documentation and rigorous tests for custom functions written in the project, you may consider organizing the project as an R package. If you do not know how to create an R package, you can easily get started in the RStudio IDE by clicking the menu File -> New Project, and selecting the project type to be an R package.

There are a lot of benefits of using an R package to manage a project. For example, you can place datasets in the data/ folder, write R code under R/, generate documentation (e.g., using roxygen2) to man/, and add unit tests to test/. When it comes to the R Markdown reports, you can write them as package vignettes under vignettes/. In the vignettes, you can load datasets and call functions in the package. When you build the package (via the command R CMD build or RStudio), vignettes will be automatically compiled.

To create a package vignette in R Markdown, the easiest way is through the RStudio menu File -> New File -> R Markdown -> From Template (see Figure 15.1). Then you select “Package Vignette” from the rmarkdown package, and you will get a vignette template. After changing the title, author, and other metadata of the template, you can start writing the content of your report.

Create a package vignette in RStudio.

FIGURE 15.1: Create a package vignette in RStudio.

If you do not use RStudio, below is what the YAML frontmatter typically looks like:

title: "Vignette Title"
author: "Vignette Author"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Vignette Title}

Note that you need to change the vignette title in both the title field and the \VignetteIndexEntry{} command. Besides the above information in the vignette, you also need to do two more things in your package DESCRIPTION file:

  1. Specify VignetteBuilder: knitr in the DESCRIPTION file.

  2. Add Suggests: knitr, rmarkdown in DESCRIPTION.

The vignette output format does not have to be HTML. It can also be PDF, so you can use output: pdf_document, too. Any other output formats that create HTML or PDF are also okay, such as beamer_presentation and tufte::tufte_html. However, currently R only recognizes HTML and PDF vignettes.