Lab 07 - R packages
Learning goals
- Build an R package.
- Use Rcpp in the package.
- Practice your GitHub skills.
Lab description
Today we will write an R package that uses Rcpp. To do so, we will use a template package that has the following set up:
Has a single Rcpp function.
Uses
roxygen2.Uses GitHub Actions for continuous integration.
The R package doesn’t have any testing in place and doesn’t have coverage checking.
Before you start
Since the package uses C++ code, you need a compiler. Run the following in R:
pkgbuild::check_build_tools(debug = TRUE)If it reports a problem, install the build tools for your system: the Xcode Command Line Tools on macOS (run xcode-select --install in the Terminal), or Rtools on Windows.
These are the functions from the lecture that you will need today. Run them from inside the package project.
| Function | What it does |
|---|---|
usethis::use_r("name") |
Creates R/name.R and opens it |
usethis::use_testthat() |
Sets up the testing infrastructure (run once) |
usethis::use_test("name") |
Creates tests/testthat/test-name.R and opens it |
usethis::use_package("pkg") |
Adds pkg to Imports in DESCRIPTION |
devtools::document() |
Updates man/ and NAMESPACE from roxygen comments (Ctrl/Cmd + Shift + D). For packages with C++ code, it also compiles the code |
devtools::load_all() |
Loads the package so you can try your functions (Ctrl/Cmd + Shift + L) |
devtools::test() |
Runs the tests (Ctrl/Cmd + Shift + T) |
devtools::check() |
Runs R CMD check (Ctrl/Cmd + Shift + E) |
Question 1: Make sure you can compile the package
Fork the following repository UofUEpiBio/egpkg, and clone it to your local computer. Once you have a copy, do the following:
Inspect its contents and the file located at
.github/workflows.GitHub does not run workflows on forks until you allow it. Go to the Actions tab of your fork and click the button to enable workflows. Otherwise, nothing will happen when you push.
Make sure you can install it using RStudio.
Run R CMD check using RStudio.
Run R CMD check using the command line (if available).
If you don’t fork it and instead downloaded it manually, make sure you set up a GitHub repository in your account to push your changes.
In RStudio, both install and check are in the Build pane (Install, and More > Check).
On the command line, go to the folder that contains
egpkg/and run:R CMD build egpkg R CMD check egpkg_1.0.tar.gz
Question 2: Adding a plot function
Here is a function and an example of how to use it:
# Here is the function
myplot <- function(x, y) {
if (!is.numeric(x) | !is.numeric(y)) {
stop("x and y must be numeric")
}
plot(x, y, col = "blue", pch = 19, cex = 2)
invisible(
list(
x = x,
y = y
)
)
}
# Here is an example
set.seed(312)
x <- rnorm(100)
y <- rnorm(100)
myplot(x, y)Add the function to the package. Notice that you will need to:
- Add only the function to the
Rfolder (not the example code). - Document it using roxygen2.
- Add the example to the documentation (using the
@examplestag). - Declare the
graphicspackage as a dependency (because of theplotfunction). - Add a test for checking that the error message is thrown when the input is not numeric.
Run devtools::check() to make sure everything works. Remember to commit and push your changes.
usethis::use_r("myplot")createsR/myplot.R. Code outside of functions in theRfolder runs every time the package is loaded, which is why the example goes under@examples.The roxygen block needs at least a title,
@param,@return, and@export.Declaring
graphicstakes two steps:- In
NAMESPACE: either writegraphics::plot()in the function, or add#' @importFrom graphics plotto the roxygen block. - In
DESCRIPTION: runusethis::use_package("graphics")to add it toImports.
- In
The package doesn’t have tests yet. First run
usethis::use_testthat(), thenusethis::use_test("myplot"). Theexpect_error()function checks that an error is thrown, and can also check its message.Run
devtools::document()after changing roxygen comments.
Question 3: Adding a C++ function
Add the ps_match function we wrote on Week 5. The linked comment has three versions (ps_match1, ps_match2, and ps_match3). Use ps_match1 and rename it to ps_match.
Add the function in a separate C++ file in the
srcfolder. Make sure to document it usingroxygen. Once you finish that, ensure it compiles and the function is visible. (then commit and push)Write an example with artificial data passing a random vector with ten elements distributed U[0, 1]. Add the example to the documentation using the
@examplestag. (then commit and push)Write a test using the
testthatR package. The C++ function should match the results of the equivalent R function:set.seed(1231) x <- cbind(runif(20)) ps_matchR <- function(x) { match_expected <- dist(x) |> as.matrix() diag(match_expected) <- .Machine$integer.max indices <- apply(match_expected, 1, which.min) list( match_id = as.integer(unname(indices)), match_x = x[indices] ) }
(then commit and push)
Leave out the
/*** R ... */block at the end of the Week 5 code. It only works withRcpp::sourceCpp().In C++ files, roxygen comments start with
//'(not#') and go above the// [[Rcpp::export]]line. Follow the format insrc/rcpp_hello_world.cpp.devtools::document()(Ctrl/Cmd + Shift + D) compiles the C++ code and updates the documentation andNAMESPACE. Then rundevtools::load_all()and tryps_match(runif(10)).For the test, create the file with
usethis::use_test("ps_match")and put the R code above at the top of it. Then compare the two functions inside atest_that()block.expect_equal()will be useful here.
Question 4: Check out the coverage of the package (if time permits)
Using the covr R package, check out the coverage using the following function
covr::package_coverage()