Skip to main content

Creating R Packages

Creating, documenting, testing, and sharing an R package using usethis, devtools, and roxygen2.
packages
functions
lecture
intermediate
LearningLearning Objectives

After completing this session, you will be able to:

  • Discuss the advantages of creating your own R package to organize code
  • Identify simple techniques for creating an R package
  • Create CRAN-compliant documentation for functions in a package
  • Write unit tests with syntax from the testthat package
  • Discuss the (dis)advantages of hosting a package in GitHub, CRAN, or R-Universe

1 Overview

Most R users are familiar with loading and using packages in their work; we’ve worked with a number of well-known packages in this course thus far! In addition, even if they mostly stick to a core set of packages, they understand the breadth of packages available on the Comprehensive R Archive Network (a.k.a. “CRAN”; the R package authority) for handling virtually any conceivable need. However, most R users have never created a package for their own work, often out of a fear that the process is too complicated. In reality, it’s fairly straighforward and super useful in your personal work. Creating packages serves two main use-cases:

  • Distribute reusable code among projects (even if just for yourself)
  • Reproducibly document analysis and models and their results

Even if you don’t plan on writing a package with such broad appeal such as, say, ggplot2 or dplyr, you still might consider creating a package to contain:

  • Useful utility functions you write (i.e., a Personal Package)
    • Having a place to put these functions makes it much easier to find and use them later.
  • A set of shared routines for your lab or research group, making it easier to remain consistent within your team and also to save time.
  • The analysis accompanying a thesis or manuscript, making it all that much easier for others to reproduce your results.