This brief tutorial accompanies the UNM Stats R Package Development “R-Hack-A-Pack”. It is intended to run through the initial steps to creating the package structure, writing documented functions, handling the package description and namespace, including data, writing package vignettes, and creating attractive documentation.

R packages

An R package is a collection of documented functions and data that can be shared as a unit.

Packages typically fall into one of three categories:

Most of you may be developing personal packages at part of this workshop. It’s a good way to keep a collection of operations you do regularly, or do rarely but are tired of searching for the code each time. As you find or develop functions useful to you, you can continue to add to your package like a toolbox.

Creating the package structure

While the new usethis package has functions to automate many package development steps, we will be using RStudio to perform these steps within the GUI.

In this example I’ll create a personal package called EBEmisc to include a set of miscellaneous functions I use regularly. Frank Harrell’s Miscellaneous Hmisc package is famous so following his example, I’m going to create one with a similar name. Please choose a good descriptive name for your real package.

Initialize package directory

I recommend creating a directory to contain your package directory as well as other materials associated with the package. My other materials usually includes a test directory and a directory to hold reference material.

./PkgDevel
  /EBEmisc
  /test
  /ref

I’ll start by creating the PkgDevel directory, and my test and ref subdirectories.

RStudio New Package

RStudio’s short tutorial is worth reading.

Make sure devtools is installed.

install.packages("devtools")
  1. Menu: File > New Project > New Directory > R Package
  2. Name your package and put it in the PkgDevel directory
    • Select Create a git repository
  3. Create Project

It will create a directory with your package name and populate it with the basic files you need for a package.

RStudio is now opened with the EBEmisc project in the upper right and the hello.R example function.

The hello.R has some documentation with keyboard shortcuts for building the package.

Go to the Build menu and select Configure Build Tools.

Select Generate documentation with Roxygen and check all the boxes. You may want to deselect Vignettes later if you have examples that take a long time to run.