Setup

Initialize project/package in RStudio

Install roxygen2 and tell R to use it

install.packages("roxygen2")

Delete NAMESPACE and hello_world files

Modify DESCRIPTION

Package: package1
Type: Package
Title: BMI Package
Version: 0.1.0
Author: Dane Van Domelen
Maintainer: Dane Van Domelen <vandomed@gmail.com>
Description: A longer description would go here.
License: GPL-2
Encoding: UTF-8
LazyData: true
RoxygenNote: 6.0.1

Create .R file for each function

#' Create BMI Groups
#'
#' Converts continuous BMI variable to BMI groups.
#'
#' @param x Numeric vector.
#'
#' @return Factor variable.
#'
#' @examples
#' bmi.vals <- rnorm(n = 50, mean = 25, sd = 3)
*' bmi3(bmi.vals)
#'
#' @export
bmi3 <- function(x) {
  bmi.groups <- cut(x, breaks = c(0, 25, 30, Inf), right = FALSE)
  return(bmi.groups)
}

Create .R file to autogenerate package help file

#' BMI Package
#'
#' A longer description would go here.
#'
#'
#' @docType package
#'
#' @author Dane Van Domelen \email{vandomed@gmail.com}
#'
#' @name package1
NULL

Build package, make sure it works

  • Build \(\rightarrow\) Check Package (optional, but often useful).
  • Build \(\rightarrow\) Clean and Rebuild.
  • Verify help files are there and functions work.
?package1
?bmi3
bmis <- round(rnorm(n = 20, mean = 25, sd = 3), 1)
bmi.groups <- bmi3(bmis)
data.frame(bmis, bmi.groups)
##    bmis bmi.groups
## 1  25.9    [25,30)
## 2  28.4    [25,30)
## 3  20.4     [0,25)
## 4  23.4     [0,25)
## 5  22.8     [0,25)
## 6  20.8     [0,25)
## 7  22.8     [0,25)
## 8  18.1     [0,25)
## 9  21.2     [0,25)
## 10 26.1    [25,30)
## 11 24.8     [0,25)
## 12 27.5    [25,30)
## 13 24.7     [0,25)
## 14 25.7    [25,30)
## 15 20.3     [0,25)
## 16 27.0    [25,30)
## 17 28.6    [25,30)
## 18 24.5     [0,25)
## 19 29.7    [25,30)
## 20 26.3    [25,30)
  • Build \(\rightarrow\) Build Source Package to generate package1_0.1.1.tar.gz file in parent directory.

Share package

Notes

  • Beauty of roxygen2 is simplicity.
    • Only edit DESCRIPTION and .R files.
    • Don’t touch anything else!
  • Adding C++ code
    • Pretty easy with Rcpp package.
    • Will cover in future article.

References

Eddelbuettel, Dirk. 2013. Seamless R and C++ Integration with Rcpp. New York: Springer. doi:10.1007/978-1-4614-6868-4.

Eddelbuettel, Dirk, and James Joseph Balamuta. 2017. “Extending extitR with extitC++: A Brief Introduction to extitRcpp.” PeerJ Preprints 5 (August): e3188v1. doi:10.7287/peerj.preprints.3188v1.

Eddelbuettel, Dirk, and Romain François. 2011. “Rcpp: Seamless R and C++ Integration.” Journal of Statistical Software 40 (8): 1–18. doi:10.18637/jss.v040.i08.

Wickham, Hadley, Peter Danenberg, and Manuel Eugster. 2017. Roxygen2: In-Line Documentation for R. https://CRAN.R-project.org/package=roxygen2.