Creating and Testing R Packages

Elaine McVey
10/23/2014

Why make R packages?

  • Because it makes your life easier.
  • Because it makes it easier to share tools internally.
  • Because it makes it easier to share tools externally.

Step 0: Get the packages you need

  • devtools (might need from github - 1.5.0.9 +)
  • testthat
  • roxygen2
  • rmarkdown
  • more?
  • much easier with RStudio!!

Step 1: Create package

  • Do NOT use package.skeleton
  • Do NOT use RStudio's “Create a new R package” (yet)
  • devtools::create(“../mypackage”)
  • this creates the .Rproj (click on it) and basic structure

Step 2: Add functions in R/

  • Then devtools::load_all()

Step 3: Edit the DESCRIPTION file

  • To add to imported (i.e. required) packages, use devtools::use_package(“dplyr”)

Step 4: Auto-generate documentation in man/

  • #' to start lines with roxygen documentation
  • @description, @param, @examples, etc.
  • @export adds functions to NAMESPACE automatically
  • devtools::document() builds documentation files
  • devtools::checkdoc() shows you what you've missed

Step 5: Make a vignette (optional)

  • devtools::use_vignette(“vignettefilename”)
  • vignettes must be self-contained to the package
  • Use Knit button in RStudio to build html

Step 6: Write tests

  • devtools::use_testthat()
  • to run the tests: devtools::test()

Why write tests?

  • Because you find and avoid bugs faster.
  • Because you can change things with confidence.
  • Because the little dots will make you happy.

Resources