Writing a package vignette with R markdown

When we develop our R package, we can also add documents in other formats than the .Rd format we talked about earlier. Normally we save them in the inst/doc folder in our package directory.

These documents are called vignettes and can be described as long-form documentation. These documents usually do not explain the package based on the functions, but on use cases or workflows we normally would use this package for. We can say that a vignette describes our package on a higher level and with more context than the classical documentation file. A definition accepted by many R users is: vignettes are optional supplemental documentation.

That is, they are in addition to the required boilerplate documentation for R functions and dataset. Vignettes are written in the spirit of sharing knowledge, and assisting new users in learning the purpose and use of a package.

Vignettes are included in many packages. We can take a look at the vignettes of our installed packages with:

browseVignettes()

This will open a web browser showing us a list of available vignettes.

Writing a package vignette with R markdown

For example, the package data.table, providing the data structure with the same name, has a vignette with the name Introduction to the data.table package in R. This is basically a tutorial showing us how to use the package and explaining all the elements step by step.

Writing a package vignette with R markdown

Every vignette contains three elements:

Before R version 3.0.0, we could just write these package vignette files in Sweave. Sweave is similar to LaTeX and sometimes pretty hard to understand. But now vignettes can also be written in other languages with the help of so-called vignette engines.

For example, the knitr package provides such an engine, which makes it possible to write vignette files in R markdown and then transform them to HTML files.

When we want to create our own vignette files, the best way to do it is using the devtools package. Load the package and call the use_vignette() function.

The console output looks like:

Creating vignette files

This function will create the folder vignettes in our package home folder. In this folder we will find the LinearRegressionHowTo.Rmd file.

Creating vignette files
Creating vignette files

The function will also take care of all dependencies that have to be adjusted to replace the Sweave engine with the knitr engine for building vignettes.

This file will then contain dummy code. But this code gives us a good overview of how we can design our own vignette.

Creating vignette files

The vignette documents written with R markdown contain three elements: the META information at the beginning of the document, the text formatted with markdown and the code examples formatted for knitr.