28 R Package Development
28.1 Prerequisites
Answer the following questions to see if you can bypass this chapter. You can find the answers at the end of the chapter in Section 28.19.
- What are the two absolutely essential files or directories required for a minimal functional R package?
- What is the primary function of the
DESCRIPTIONfile? - What is the main distinction between packages listed under
Importsand those listed underSuggests?
28.2 Learning objectives
By the end of this chapter you should be able to:
- Create a skeletal R package with
usethis::create_package()and add the canonical development tooling (use_git,use_testthat,use_readme_rmd,use_mit_license). - Structure code in
R/, data indata/, and tests intests/testthat/. - Document a function with
roxygen2tags and generate.Rdfiles withdevtools::document(). - Manage dependencies in
DESCRIPTIONusingImports,Suggests, andDepends. - Manage exports through the auto-generated
NAMESPACE, with@exportand@importFromroxygen tags. - Install a package from source, from a local directory, and from GitHub.
- Run
devtools::check()and resolve common warnings.
28.3 Orientation
Everything written so far in this book has been a script. A script is a set of instructions that runs top-to-bottom and ends. A package, by contrast, is a reusable library of functions with documentation, tests, and a dependency declaration. Packages are how analytical work scales beyond a single analyst and a single project.
The modern foundation for R package development is the book R Packages (2nd ed.) by Wickham and Bryan, together with the usethis and devtools packages it documents. The workflow they describe has become the standard, and this chapter follows it.
In this chapter we shall carry that workflow as far as a buildable, installable, documented package. We begin with the case for packaging code and with usethis::create_package(). We then cover the package structure, roxygen2 documentation, and the dependency fields of DESCRIPTION. Lastly, we turn to installation, R CMD check, and vignettes, and we close with a worked example. The testing infrastructure that makes packages maintainable is taken up in the next chapter, on testing.
28.4 The statistician’s contribution
Package development looks like software engineering, and it is. However, the judgments specific to statistical packages concern audience and scope.
Who will use this? A package for one’s own analysis needs little more than working code and a DESCRIPTION. A package for a research group needs documentation and tests. A package for the public CRAN repository needs clean dependencies, vignettes, and continuous integration. We would pick the audience first; the engineering follows from it.
What goes in the package, and what stays in the analysis? A function reused across two projects belongs in a package; one used once does not. Similarly, a regression diagnostic that comes up in every analysis is a candidate, while a one-off plot for one paper is not. The boundary is fuzzy. A useful heuristic is that anything one would otherwise copy and paste between projects is a packaging candidate.
Documentation as a contract. The roxygen comment above a function is a promise about its behavior. That is, it states what arguments the function takes, what it returns, and what conditions it expects. Vague documentation produces confused users and bug reports about expected behavior. Specific documentation, including the edge cases the function does or does not handle, saves time over the package’s life.
Dependencies are a tax. Each package listed under Imports becomes something users must install. Each version restriction (dplyr (>= 1.0.0)) constrains the environments in which the package will work. On the one hand, a minimum-viable dependency list saves friction. On the other, the maximalist ‘use whatever is convenient’ approach produces packages that are hard to install five years later.
28.5 Why package code?
The concrete benefits are five:
- Reuse. A function in a package is loaded with
library(yourpkg); a function in a script is sourced by hand or copy-pasted. - Documentation. Roxygen comments produce help pages accessible via
?function_name, indistinguishable from base R or CRAN package help. - Tests. Packages have a canonical home for tests (
tests/testthat/); scripts do not. - Dependency management.
DESCRIPTIONdeclares what the package needs; users install dependencies automatically. - Distribution. A
.tar.gzbuild can be installed by others. CRAN, GitHub, and internal package servers all use this format.
Against these benefits, packaging adds files, conventions, and tooling. The threshold for going from script to package is roughly ‘this code will be reused by me or someone else more than once’.
28.6 usethis::create_package() and first commit
library(usethis)
# create the skeleton in a new directory
create_package("~/research/phb228utils")This creates:
DESCRIPTION(metadata)NAMESPACE(export declarations; auto-generated)R/(source code directory; empty)phb228utils.Rproj(RStudio project file).Rbuildignore(files to exclude from package build).gitignore(files to exclude from version control)
We then add the standard scaffolding:
use_git() # initialize git repository
use_github() # create a GitHub repository
use_mit_license() # add an MIT license
use_readme_rmd() # README that knits to README.md
use_testthat() # set up the testing framework
use_news_md() # NEWS.md for changelogEach of these calls adds files in canonical locations and updates DESCRIPTION and .Rbuildignore as needed. Doing all of this manually is tedious and error-prone, and usethis encodes the conventions for us.
28.7 Package structure
phb228utils/
├── DESCRIPTION # metadata
├── NAMESPACE # auto-generated by roxygen2
├── R/ # source code
│ ├── summarise.R
│ ├── plot.R
│ └── package.R # package-level documentation
├── man/ # auto-generated by roxygen2
│ └── *.Rd
├── tests/
│ ├── testthat.R
│ └── testthat/
│ └── test-summarise.R
├── vignettes/
│ └── intro.Rmd # long-form documentation (optional)
├── data/ # binary R data files (.rda)
├── data-raw/ # scripts that create data/*.rda (not shipped)
├── inst/ # other files shipped with the package
├── LICENSE
├── README.md
├── NEWS.md
└── phb228utils.Rproj
What goes where:
R/: source code. One function per file is a common convention (R/summarise.Rforsummarise()). Files are loaded in alphabetical order; if some functions depend on others, use@includeroxygen tags or merge into one file.man/: auto-generated.Rddocumentation files. Never edit these by hand; edit the roxygen comments and re-rundevtools::document().tests/testthat/: test files (covered in Chapter 29).data/: example datasets shipped with the package, loaded withdata(my_data).vignettes/: long-form articles built with the package and accessible viavignette("intro", "phb228utils").
28.8 roxygen2 documentation
Documentation lives in comments placed above each function. To illustrate, consider a function that summarizes a numeric vector:
#' Summarize a numeric vector
#'
#' Produces a tibble with the mean, standard deviation, and
#' quartiles of a numeric vector, ignoring missing values.
#'
#' @param x A numeric vector.
#' @param probs Quantile probabilities to report. Defaults
#' to `c(0.25, 0.5, 0.75)`.
#' @return A tibble with one row and columns `mean`, `sd`,
#' and one column per requested quantile.
#' @export
#' @examples
#' summarise_numeric(rnorm(100))
#' summarise_numeric(rnorm(100), probs = c(0.05, 0.5, 0.95))
summarise_numeric <- function(x, probs = c(0.25, 0.5, 0.75)) {
stopifnot(is.numeric(x))
q <- quantile(x, probs = probs, na.rm = TRUE)
tibble::tibble(
mean = mean(x, na.rm = TRUE),
sd = sd(x, na.rm = TRUE),
!!!setNames(as.list(q), paste0("q", probs * 100))
)
}The commonly used tags are as follows.
@param name description: each argument.@return description: what the function returns.@export: the function is part of the package’s public API.@examples: runnable examples; checked byR CMD check.@importFrom pkg fn: import a specific function from another package.@seealso: links to related functions.@inheritParams other_function: copy parameter docs from another function.
After editing roxygen comments, we regenerate the .Rd files and NAMESPACE:
devtools::document()This is one of the most common commands in package development, and it is worth binding to a keystroke.
28.9 DESCRIPTION: Imports, Suggests, Depends
A typical DESCRIPTION file reads as follows.
Package: phb228utils
Title: Helper Functions for Statistical Computing
Version: 0.1.0
Authors@R:
person(family = "rgtlab curriculum team", email = "rgthomas47@gmail.com",
role = c("aut", "cre"))
Description: Reusable helpers for the PHB 228 statistical
computing course textbook.
License: MIT + file LICENSE
Encoding: UTF-8
LazyData: true
Imports:
dplyr (>= 1.0.0),
tibble,
rlang
Suggests:
testthat (>= 3.0.0),
knitr,
rmarkdown
RoxygenNote: 7.3.2
The three dependency fields differ as follows.
Importsare mandatory. The packages whose functions are called in exported code go here, andlibrary(yourpkg)will fail if they are not installed. Imported functions may be called explicitly withpkg::fn()(best practice) or made available unqualified with@importFrom pkg fn.Suggestsare optional. They are used in vignettes, tests, examples, or by features that gate themselves onrequireNamespace("pkg", quietly = TRUE). The package must work without them.Dependsis for packages that should be loaded whenever yours is loaded (solibrary(yourpkg)also loads them). We would avoid it, because it pollutes the user’s namespace, and useImportsinstead.
A dependency is added with usethis::use_package():
use_package("dplyr") # adds to Imports
use_package("testthat", "Suggests")For version requirements, we use minimum versions for the features we need, not exact pins. dplyr (>= 1.0.0) means ‘any version 1.0 or later’. We would avoid dplyr (== 1.0.5), since it constrains users to one specific version, which usually breaks within a year.
28.10 Installing and loading
During development:
devtools::load_all() # simulate library(yourpkg) without installingload_all() makes the package’s functions available in the current R session, including non-exported ones, so that we can call internal functions for testing. It is the fastest way to iterate on changes.
To install for real use:
devtools::install() # build and install in user's library
devtools::build() # build a .tar.gz for distributionFor a package on GitHub:
remotes::install_github("yourname/yourpkg")Or from a local source directory:
install.packages("/path/to/yourpkg.tar.gz", repos = NULL,
type = "source")Before submitting the package to anyone (CRAN, a collaborator, or our future selves), we run the standard checks:
devtools::check()This runs R CMD check, the standard test of package quality. It checks that:
- Documentation is complete and consistent.
- Examples run without errors.
- Tests pass.
- Dependencies are declared correctly.
- Exported functions are all documented.
- The package builds and loads on a clean R session.
A clean check() (no errors, warnings, or notes) is the goal for any shareable package.
28.11 Common R CMD check warnings
‘no visible binding for global variable’ arises when we use column names with non-standard evaluation (NSE) inside functions. It is common in dplyr code, where dplyr::filter(data, year == 2020) references year without quoting. One fix is to place the following declaration
utils::globalVariables(c("year", "treatment"))at the top of one of the package’s R/ files. The preferred alternative is to use .data$year and .data$treatment.
‘undefined exports’ arises when an @exported function does not exist. The remedy is to re-run devtools::document().
‘package required but not declared’ arises when we use pkg::fn() for a package not listed in Imports. The remedy is to add it.
‘examples lines wider than 100 characters’ arises when an example line is too long. The remedy is to break it up.
28.12 Vignettes
A vignette is a long-form article packaged with the code. It is created with:
use_vignette("intro")This creates vignettes/intro.Rmd with a template. We edit it, build it with devtools::build_vignettes(), and access it in R with vignette("intro", "phb228utils").
Vignettes are how we teach users why and how to use the package, beyond the function-by-function reference. For an analysis package, the vignette is often a worked example.
28.13 Worked example: a small package
To illustrate the full workflow, consider the following sequence for a small package.
# 1. create the package
usethis::create_package("~/research/phb228utils")
# 2. add tooling (run from inside the new package)
usethis::use_git()
usethis::use_mit_license()
usethis::use_testthat()
usethis::use_readme_rmd()
# 3. add a function
# in R/summarise.R:
# roxygen header above summarise_numeric()
usethis::use_package("tibble")
# 4. document and check
devtools::document()
devtools::load_all()
?summarise_numeric
# 5. add a test
usethis::use_test("summarise")
# write the test, run:
devtools::test()
# 6. install
devtools::install()This sequence creates a working, documented, tested, installable package in about thirty minutes of focused work.
28.14 Collaborating with an LLM on package development
Package development has many conventions. LLMs handle most of them reasonably well and stumble on a few specific ones. We consider three representative prompts.
Prompt 1: drafting a roxygen header. We paste the function and ask: ‘write a roxygen2 header with @param, @return, @export, and @examples. The example should be a realistic, runnable use of the function.’
What to watch for. The example needs to actually run. A common LLM error is an example that uses a variable that is not defined. We would run the example ourselves before committing.
Verification. We run devtools::document() and then run the example via ?function_name. If the example fails, we fix it.
Prompt 2: diagnosing an R CMD check warning. We paste the warning verbatim and ask: ‘what does this mean and how do I fix it?’
What to watch for. The standard warnings (global variables, undocumented arguments, missing imports) have known fixes, and LLMs handle them well. Less common warnings (invalid CITATION format, vignette engine issues) get mixed answers. For these we verify against the R packages book or the CRAN policies.
Verification. We apply the fix and re-run check(). If the warning persists, we look up the message in the R packages book.
Prompt 3: deciding Imports vs Suggests. We describe how a dependency is used (e.g., ‘I call ggplot2::ggplot inside one of my exported functions; I also use it in a vignette’). We then ask: ‘should this be in Imports or Suggests?’
What to watch for. The rule is ‘Imports if exported code uses it’. Vignette-only or test-only dependencies go in Suggests. The LLM should know this rule; if it hesitates, we push for the rule.
Verification. We try installing the package on a fresh R session without the dependency installed. If library(yourpkg) fails, the dependency belongs in Imports.
28.15 Principle in use
Three habits define defensible package development:
- Use
usethisfor scaffolding. Hand-creating the package skeleton is error-prone and wastes time, whereasusethisencodes the canonical layout and conventions. - Document every exported function. A roxygen header with
@param,@return, and a runnable@examplesis the contract with users. - Aim for a clean
R CMD check. That is, the check should report no errors, warnings, or notes. The output ofcheck()is the first thing CRAN reviewers (and any thoughtful collaborator) look at.
28.16 Exercises
- Create a package
phb228utilswith a single functionsummarise_numeric()as defined in this chapter. Document it, add an example, and confirm that?summarise_numericworks afterdevtools::document()anddevtools::load_all(). - Add a dependency on
dplyrtophb228utils. Decide whether it belongs inImportsorSuggestsand justify your choice. - Build the package as a
.tar.gzwithdevtools::build()and install it on a clean R session. Verify it works. - Run
devtools::check()on the package. Fix every warning and note until the output is clean. - Write a vignette demonstrating
summarise_numeric()on a real dataset. Build the vignette and access it viavignette().
28.17 Further reading
- (Wickham & Bryan, 2023), R Packages, 2nd ed., the canonical reference. Free at r-pkgs.org. Tracks the modern
usethis/devtoolsworkflow. - The
usethisanddevtoolspackage documentation. - Writing R Extensions (the official R-core manual) for the technical reference; usually a last resort, but authoritative when conflicts arise.
28.18 Practice test
The following multiple-choice questions exercise the chapter’s content. Attempt each question before expanding the answer.
28.18.1 Question 1
What are the two absolutely essential files/directories required for a minimal functional R package?
DESCRIPTIONfile andman/directory
DESCRIPTIONfile andR/directory
NAMESPACEfile andR/directory
R/directory andtests/directory
B. DESCRIPTION provides metadata; R/ contains source code. All other components (NAMESPACE, man/, tests/) are either auto-generated or optional.
28.18.2 Question 2
What is the primary function of the DESCRIPTION file?
- To contain the actual R function code
- To store example datasets
- To provide essential package metadata including dependencies, author information, and version numbers
- To automatically generate help documentation
C. DESCRIPTION stores package metadata including Imports, Suggests, Depends, Author, Version, and License.
28.18.3 Question 3
What is the main distinction between packages listed under Imports versus Suggests?
Importslists packages required for core functionality;Suggestslists optional packages for enhanced features
Importsrefers to newer packages;Suggestsrefers to older, deprecated ones
Importsindicates packages from CRAN;Suggestsindicates packages from GitHub
- There is no meaningful difference
A. Imports packages are mandatory dependencies; Suggests packages are used only for optional features (vignettes, tests, examples) and need not be installed by default.
28.18.4 Question 4
You add @export above one function and not above another. What does this mean?
- Only the
@exported function is part of the package’s public API; the other is internal.
- Only the
- Both are public;
@exportis a stylistic choice.
- Both are public;
- The non-exported function is broken.
- The exported function is loaded faster.
A. Internal functions are accessible only via pkg:::fn() and may change without notice; exported functions are the package’s stable public API.
28.18.5 Question 5
After modifying a roxygen header above a function, you should next:
- Edit
man/function.Rddirectly to match.
- Edit
- Run
devtools::document()to regenerate the.Rdfile andNAMESPACE.
- Run
- Manually update
DESCRIPTION.
- Manually update
- Restart R.
B. devtools::document() regenerates documentation and the namespace from roxygen comments. Hand-editing the .Rd files is a mistake, since they will be overwritten.
28.19 Prerequisites answers
- The
DESCRIPTIONfile (metadata) and theR/directory (source code). Everything else (NAMESPACE,man/,tests/,data/, vignettes) is either auto-generated or optional. The minimum viable package is one function inR/foo.Rplus a shortDESCRIPTIONholding the required fields. DESCRIPTIONstores package metadata: name, version, title, description, author, license, and the package’s dependencies (Imports,Suggests,Depends). It is the file that distinguishes a package from a directory of R scripts.Importslists packages required for core functionality (they must be installed for the package to work).Suggestslists packages used only for optional features (vignettes, tests, examples) and need not be installed by default. The rule of thumb is as follows. If your exported code callspkg::fn(), the package goes inImports. If only your tests, vignettes, or optional features use it, the package goes inSuggests.