16.7 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 the roxygen2 package (Wickham, Danenberg, et al. 2022)) 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 16.4). 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 16.4: Create a package vignette in RStudio.

Alternatively, you can install the package usethis (Wickham, Bryan, and Barrett 2022) and use its function usethis::use_vignette() to create a vignette skeleton. Below is what the YAML frontmatter of a package vignette 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.


Wickham, Hadley, Jennifer Bryan, and Malcolm Barrett. 2022. Usethis: Automate Package and Project Setup.
Wickham, Hadley, Peter Danenberg, Gábor Csárdi, and Manuel Eugster. 2022. Roxygen2: In-Line Documentation for r.