Vaughan, Hester, and François (2024) is better used when adding C++ code to R packages, as it allows for proper script organization and documentation. The reference for this chapter is Wickham et al. (2024).
Loading the Required R Packages
This chapter and the next use the following R packages:
It is possible to run a single function in C++ using the cpp11::cpp_source() function. For example, to create a function that adds one to a number, you can run:
cpp11::cpp_source(code =" #include <cpp11.hpp> using namespace cpp11; [[cpp11::register]] int plusone(int x) { return x + 1; }",quiet =FALSE)
Within R, there is no need to create a main() function in C++.
The R version of the function is as follows:
#' Return 1 (R)#' @exportone_r <-function() {1L}
To export the C++ function, I added the following lines to ece244-package.R, which documents the function and allows for defining default argument values:
#' Return the sign of a number (R)#' @param x integer#' @exportsign_r <-function(x) {if (x >0) {1 } elseif (x ==0) {0 } else {-1 }}
I also added the corresponding auxiliary function for documentation:
#' Return the sign of a number (C++)#' @inheritParams sum_r#' @exportsign_cpp <-function(x) {sign_cpp_(x)}
Installing the Package
To document and install the package as an R library, I ran the next functions:
cpp_register()document()install()
Afterward, I could access the functions by loading the package with library(ece244).
For development and live testing, I used the load_all() function:
load_all()
Each time I had to make changes to the C++ code, I ran load_all() again to test and then reinstalled the package.
Good Practice
It is good practice to include a license for your code. For example, you can use the Apache license by running:
use_apache_license()
Additionally, it is recommended to use use_build_ignore() to ignore files that are unnecessary for package installation. For example, to ignore the docs folder, you can run:
use_build_ignore("docs")
My .Rbuildignore file includes the following lines, which I edited manually to exclude specific files and directories: