Chapter: 3 Packages

R packages are the vehicle for distributing working code to other users and their machines. Building a package turns a developer’s human readable code into binary that can be transfered to another user’s computer, and then installed so that package becomes available to the user.

3.1 Install Development Tools

Buiding an R package requires extra development software that does not come with R or RStudio.

3.1.1 Mac: XCode

In your terminal, execute xcode-select --install, and if you are prompted to install command line developer tools, select “Install” and “Agree”.

3.1.2 Windows: Rtools

Download and run the recommended Rtools.exe file from https://cran.r-project.org/bin/windows/Rtools/ with the default selections.

3.1.3 Linux: R development tools package

Install the R development tools package corresponding to your system.

3.1.4 Verify Success in RStudio Console

library(devtools)
has_devel()

3.2 Rules and Best Practices:

  • All external packages you use inside your package should be listed under the Imports: field in the DESCRIPTION file. This is what makes them available to to your code.
  • Use explicit package::function notation when calling a function from another package
  • If you are using a particular function a lot, you may add @importFrom package function to the roxygen block to avoid using the above explicit notation
  • If you are writing a function to be used by a user of the package, you have to export it. You can do this by placing @export in the roxygen block which is discussed in 5

3.3 Building the package

3.3.1 When?

You should always clean and build the package (and resolve any errors or warnings) before making a commit.

3.3.2 Clean

In the RStudio Toolbar, select “Build” >> “Clean”. This removes unneccesssary files that were created from a previous build.

3.3.3 Build

R CMD check in the terminal, devtools::check() in the console, and Ctrl/Cmd + Shift + E in RStudio all deploy a function that checks your package for common problems and makes sure a package includes everything in needs to play well with others upon distribution.

Errors and warnings produced by the check() funciton should be resolved before every commit. This workflow comes from the book R packages (Wickham and Bryan 2019):

  1. Run the devtools::check() function
  2. Fix the first error or warning
  3. Repeat steps (1) and (2) until all errors and warnings are resolved.
  4. Now in order to be able to use the package, use the devtools::install() function or Ctrl/Cmd + Shift + B to load the current version of the package into RStudio.

References

Wickham, Hadley, and Jennifer Bryan. 2019. R Packages. https://r-pkgs.org/.