R Packages

Ranae Dietzel and Andee Kaplan

Let’s make an R package!

Content for today is from Hadley’s book and Eric’s ISU Graphics Group talk.

Why Packages?

Requirements

  1. devtools (install.packages("devtools"))
  2. roxygen2 (install.packages("roxygen2"))

Some other potentially useful packages include:

Ready?

We can check:

library(devtools)

has_devel()
## '/usr/local/Cellar/r/3.3.2/R.framework/Resources/bin/R' --no-site-file  \
##   --no-environ --no-save --no-restore --quiet CMD SHLIB foo.c
## 
## [1] TRUE

Naming your Package

From http://r-pkgs.had.co.nz/package.html:

The DESCRIPTION File

This is the overall descriptor of the package from which metadata is obtained. Fields include:

And more…

The NAMESPACE File

Defines the imported functions (dependencies), and exported functions

What are exported functions?

The R Directory

Contains the R code for the package. This can be done in a few ways:

  1. Put all functions into a single file
  2. Have a separate file for each function
  3. Group similar functions together in separate files

The third is recommended by Hadley and is generally the approach that should be used, although CRAN gatekeepers prefer the second option at least compared with the first.

The man Directory

roxygen2

It allows automatic generation of:

It creates the NAMESPACE and Rd files automatically for us. We just have to add special comments above each function.

Let’s take a look…

Checking, Installing, Building

There will be three general routines we use devtools for: checking (verifying that the package is in the proper format), installing (installing it on our own computer), and building (building it for use by other people)

# With your working directory set to the root package folder
devtools::check()
devtools::install()
devtools::build()

Package Dependencies

Sometimes we need to depend on other packages. To do so, we use the @import or @importFrom directive in roxygen. Let’s look at an example.

Your Turn

Add a new function of your choosing to the package. The function must:

  1. Import the ggplot2 package (@import ggplot2)
  2. Return a ggplot2 plot of your choosing
  3. Be exported
  4. Take at least two parameters which are both documented

When you have created this function, check and install your package to make sure that it works!

GitHub

In the real world, we’re usually developing packages with other developers. Collaborative coding tools like GitHub make this much easier.

As a side benefit, putting your package on GitHub makes installing the package much easier as well:

devtools::install_github("andeek/agron590demo")