We are going to learn how to create an R package with unit testing and documentation.
We will use the packages devtools, usethis and roxygen2.
Create Package
First we will create the scaffold of the package. In an R session write:
> usethis::create_package("myRpackage")
This will create the following files inside the myRpackage directory:
- man : Directory for man pages
- R: Directory where you will place your code
- DESCRIPTION: File with a description of your package like author, dependencies, etc. You should edit this file.
- NAMESPACE: File generated by roxygen2. Do not edit.
Write code
We create the file my_functions.R in the myRpackage/R directory
#' Calculate mean function #' #' This function allows you to calculate the mean of a sequence vector. It interpolates the missing values. #' @param v vector #' @import zoo #' @examples #' calc_mean(c(1,3,NA,6,7)) #' #' @return mean #' @export calc_mean<-function(v){ m<-calc_sum(na.approx(v)) m/length(v) } calc_sum<-function(v){ s<-0 for (x in v){ s<-s+x } s }
This will create and export the function calc_mean() from the package.
Documentation
The comments are written to be undertood by roxygen2. Here you can check some tutorial on how it works. The official documentation is here.
Enter into the myRpackage directory, for example with setwd(“myRpackage”).
You can create documentation inside an R session with:
> devtools::document()
This will create a file ./man/calc_mean.Rd with the help information and will edit the NAMESPACE file. The NAMESCPACE tells which function is exported and which libraries have to be imported.
Testing
In the directory myRpackage in the R console write:
> usethis::use_testthat()
This will create the tests/testthat directory and tests/testthat.R file.
To create a new test you can use the command usethis::use_test
> usethis::use_test("calc_mean")
This will create the file ‘tests/testthat/test-calc_mean.R’ that you can edit:
context("test-calc_mean") test_that("testing my app", { expect_equal(calc_mean(c(1,3,NA,6,7)), 4.3) })
Execute testing with the R command devtools::test():
> devtools::test() Loading myRpackage Testing myRpackage ✔ | OK F W S | Context ✔ | 1 | test-calc_mean ══ Results═════════════════════════════════════════ Duration: 0.1 s OK: 1 Failed: 0 Warnings: 0 Skipped: 0 Way to go!
Building
You can build the document from an R console with the command:
>devtools::build()
Or from the parent directory you can execute from the shell:
$ R CMD build myRpackage
* checking for file ‘myRpackage/DESCRIPTION’ ... OK
* preparing ‘myRpackage’:
* checking DESCRIPTION meta-information ... OK
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
* building ‘myRpackage_0.1.tar.gz’
Install the package
To install the package just write from the shell:
$ R CMD INSTALL myRpackage_0.1.tar.gz