Package vignettes

How to build package vignettes with knitr

2012-01-22

Since R 3.0.0, non-Sweave vignettes are officially supported. Please see the section “Non-Sweave vignettes” in the manual “Writing R Extensions”. Basically what you need to do for package vignettes are:

  1. Add %\VignetteEngine{knitr::knitr} and %\VignetteEncoding{UTF-8} to the vignette source document. Also specify the vignette index entry with %\VignetteIndexEntry{}.
  2. Specify VignetteBuilder: knitr in the package DESCRIPTION file.
  3. Add Suggests: knitr in DESCRIPTION if knitr is needed only for vignettes. If your vignette is R Markdown, you also need rmarkdown in Suggests.

Vignette engines

Then all your vignettes will be compiled by knitr instead of the default engine Sweave. The vignette engine knitr::knitr is only one of possible engines in knitr. To see all of them, run

library(knitr)
library(tools)
names(vignetteEngine(package = 'knitr'))
# for example:
# "knitr::rmarkdown" "knitr::knitr" "knitr::docco_classic" "knitr::docco_linear"
# "knitr::knitr_notangle" ...

The engines with the suffix _notangle have the same weave functions as those without the suffix, but have disabled the tangle function, meaning that there will not be R scripts generated from vignettes during R CMD build or R CMD check. See here for a discussion on why sometimes we may not want to tangle R scripts from vignettes (basically it is redundant for R CMD check to run the same code again after the code has been executed in weave, and currently the inline R code expressions are not included in the tangle output, which can cause problems).

Examples

All the document formats that knitr supports can be used for package vignettes (e.g. R Markdown). I have some examples in the knitr package, and many other packages on CRAN also contain knitr vignettes.

Command-line usage

Since R 3.1.0, any document that has specified the vignette engine via %\VignetteEngine{} can be compiled through the command line R CMD Sweave. This is not restricted to Sweave documents or R package vignettes.

A note to devtools/remotes users

Note devtools and remotes do not build vignettes by default when you use them to install packages (e.g., using remotes::install_github()). You have to specify the argument build_vignettes = TRUE when you install the package. Currently there is no way to build vignettes using devtools if you just use the RStudio button Install & Reload. You have to Build Source Package, and run R CMD INSTALL on the tarball. Or run remotes::install_local(build_vignettes = TRUE) in the R console.

Acknowledgment

I really appreciate the generous support by one of the R core members Duncan Murdoch as well as the hard work by Henrik Bengtsson.