Compartmentalized Documented Extendible Reproducible Robust

This week I will cover more advanced topics regarding R packages:

  • How to use the “check” feature to find problems in your package.
  • How to write a vignette for your package.
  • How to write print and plot functions for your objects.
  • Using pkgdown to make a website for your package.

If/when you want to go into R packaging in more depth, work through the material from this R package workshop material. You’ve seen much of this material so it should be somewhat familiar. See also Hadley Wickham’s book R Packages.

The repository that I used to demo these features is here: https://github.com/eeholmes/MyNewPackage

Checking your package

Just use the RStudio Check in the Build tab. You’ll have many issues (most likely). Plug away at each one until you pass with no errors or warnings. Don’t ignore Notes either. They are sometimes more serious than the errors and warnings.

If R asks you to update packages, and then proceeds to fail at installation because of a warning that a package was built under a later R version than you have on your computer, use

Sys.setenv(R_REMOTES_NO_ERRORS_FROM_WARNINGS=TRUE)

Creating print and plot methods for your objects

Make your output an object

littleforecast <- function(data, nyears=10){
  fit <- forecast::auto.arima(data)
  fc <- forecast::forecast(fit, h = nyears)
  ggplot2::autoplot(fc)
  class(fit) <- c("foo", class(fit))
  return(fit)
}

plot method

#' Plots foo object
#'
#' Plots foo object.
#'
#' @param x An foo object.
#' @param ... Not used.
#' @method plot foo
#' @export
plot.foo <- function(x, ...) {
  plot(1:10)
}

Note, plot() is part of the graphics package so you need to add that to Imports in your DESCRIPTION file. Our Imports line is now:

Imports: forecast, graphics

Add your methods to your namespace

S3method(print,foo)
S3method(plot,foo)

Example

Install and restart MyNewPackage.

fit=littleforecast(WWW2)
fit
plot(fit)

Writing a vignette

Doing this in RStudio is easy. See rmarkdown vignette chapter and Hadley’s vignette chapter for more info.

Making the vignette

Manually

  • Make a vignettes folder at the base level (same level as the R folder)
  • Create a new vignette file from a template. RStudio > File > New > R Markdown > From Template > Vignette
  • Save in vignettes folder
  • Change the title in the 2 places in the yaml at the top. ‘yaml’ is between the --- fences.
  • Add the following 2 lines to your DESCRIPTION file:
Suggests: knitr, rmarkdown
VignetteBuilder: knitr

Or use a helper function:

devtools::use_vignette("my-vignette")

or

usethis::use_vignette("MyNewPackage")

Testing your vignette

Open your vignette file and click the Knit button.

Getting your vignette to show up

Once you have your vignettes in the vignettes folder, you’l like to be able to build them and have them appear when you type browseVignettes("MyNewPackage"). This will not work. In fact, RStudio seems to actively hinders this workflow.

Vignettes can take a long time to build and by default when R builds a package from source (which is what Install and Restart on the build tab does), it does not re-make your vignettes. You can make RStudio re-make your vignettes in the vignettes folder (if the Rmd file changes) using Tools > Project Options > Build Tools > Generate documentation with Roxygen > Configure and clicking the vignettes check-box. But this will not get your vignettes loaded when you click Install and Restart on the Build tab (browseVignettes() still won’t work).

So how does R know about your vignettes when it is building from source (i.e. from Install and Restart in the Build tab in RStudio)? It needs the vignette files (.Rmd, .R and .html) in the inst/doc folder. How do you get them there? You have to put them there.

That’s easy. I’ll just put them there whenever I change or add vignettes. Unfortunately, the default RStudio default behavior is to delete the whole inst/doc folder whenever you click Check (package) in the Build tab. It’s happening because the default is to use devtools::check() and there is no way to set devtools::check(vignettes=FALSE). To stop RStudio from deleting inst/doc on package checking, uncheck the use devtools package functions if available box. You may also want to add --no-manual to the R CMD Check options box since that is the default for devtools::check().

This is my vignette workflow:

  • Create the vignette folder and add vignette Rmds to it using the R Markdown vignette template in RStudio.
  • Create the inst folder in my package at the base level (same level as the R folder).
  • Edit my vignette Rmd and use the Knit button to preview.
  • When I am done, run the following code to update the vignette files and copy to the inst/doc folder.
tools::buildVignettes(dir = ".", tangle=TRUE)
dir.create("inst/doc")
file.copy(dir("vignettes", full.names=TRUE), "inst/doc", overwrite=TRUE)

Once your vignette files are in inst/doc, Install and Restart button will add the vignettes to your package and install_github() will have them too.

Careful, RStudio Check in the Build tab will delete the inst/doc folder and not recreate it. So always check that inst/doc not been trashed and uncheck the use devtools package functions checkbox on the Build > More > Configure Build Tools… window. You will most likely also want to add --no-manual to the R CMD check additional options box.

pkgdown

pkgdown makes it easy to make nice webpages for your packages.

Depends versus Imports

@Depends These packages that will be loaded when your package is loaded. So if you have gplot2 in @Depends, like above, then the user automatically can use ggplot2 functions without issuing the command library(ggplot2).

@Imports Are required for the package functions, but the user will not have access to the functions without calling library(...). In your package, you will use :: to access the functions from the packages on the @Imports line. Most of your package dependencies will be here.

To limit the number of headaches that users face when trying to install your package, use as few packages on your @Depends and @Imports lines in DESCRIPTION file as possible. If your package does not need the package to work, then put the package on @Suggests.

I have R packages that are mainly for my personal use. I use the package to make sure I have access to the various packages that I’ll be using. So for example, if I am doing work on my sardine papers, I have set of packages that I use. When I issue the command library(SardineForecast) a bunch of packages are loaded. This makes it handy for me, but all those dependencies makes it a huge hassle to install the package from GitHub for my collaborators (and even a hassle for me to install from GitHub). Huge Hassle. Invariable one of the 15 packages that I need will itself have a dependency that won’t load and then I have to debug that. If I need collaborators, who are on different operating systems and various versions of R to install it, it’s a suffer-fest.

For my MARSS package, I have only 3 non-base dependencies in the @Imports line and nothing on the @Depends line besides R. The imports are KFAS, mvtnorm, and nlme. Then on the @Suggests line, I have a bunch of packages that are used in the vignettes. MARSS is easy to install from GitHub (though it is also hosted on CRAN).

What should you put on your Depends and Imports lines?

First off, when you are starting, don’t worry too much about this. Just add packages that are needed as you work on your functions.

  • ALWAYS use :: to use functions from other packages in your package functions. Seriously. You will save yourself so many headaches down the road by being able to search for xyzpackage:: to find all that packages functions. Why? Trust me, one day you will want to swap out packages or remove dependencies. Note, this can be a hassle with functions like ggplot() which use functions within their calls and you have to use :: everywhere. Like so

    ggplot2::ggplot(df) +
       ggplot2::geom_point(ggplot2::aes(gp, y))

    Arg. Another example is say a GAM call:

    mgcv::gam(a ~ mgcv::s(b), data=df)

    But this is just for your package functions. In your scripts, you’d probably use a library() call.

  • Never ever use library() in a function! Use xyzfunction::function. Sure use library() in your scripts, but never in a package function. When you add a function from a new package to your function, add those packages to @Depends or @Imports in your DESCRIPTION file as you go along.

  • Every so often check that you don’t have packages on @Depends and @Imports that you don’t use. Just do a Edit > Find in Files… search for xyzpackage:: to find out if you are still using xyzpackage.

  • How do you know if you forgot a dependency or forgot a :: somewhere? Two ways:

    1. Do Session > Restart R to close all your loaded packages. Then load your package with library(yourpackagename) and try your functions. Things will fail if you have a package in @Imports but forgot a :: somewhere.
    2. From the Build tab, use More > Check Package. That should show package dependency errors (plus a whole slew of other problems for you to work through).

Styling your code

You should stick with a uniform style guide to make your code easier to follow. I use the tidyverse style guide with the styler R package. styler has an RStudio Addin which does all the work of styling my code for me. Install the package, restart RStudio, and then go to Tools > Addins > Browse Addins. Scroll down to styler, and select the file(s), you want to style.

Byte Compile

Adding this line to your DESCRIPTION file can really speed up your code. This is one of the advantages of putting your functions in a package. It can actually make your functions faster.

ByteCompile: TRUE

NWFSC Math Bio Program