Statisticians Advancing in R
for Data Science
Marquette University
STAR-DS - SDSS 2026
evalCpp() & cppFunction()sourceCpp()Advantages:
evalCpp()evalCpp() evaluates a single C++ expression. Includes and dependencies can be declared.
This allows us to quickly check C++ constructs.
cppFunction()Rcpp::cppFunction("
bool isOdd_cpp(int num = 10) {
bool result = (num % 2 == 1);
return result;
}")
c(isOdd_cpp(42L), isOdd_cpp(43L))
># [1] FALSE TRUEcppFunction() in R console or scriptLet’s consider a simple possible \(VAR(1)\) system of \(k\) variables.
For \(k = 2\):
\[ X_t = X_{t-1} B + E_t \]
where \(X_t\) is a row vector of length \(2\), \(B\) is a \(2×2\) matrix, and \(E_t\) is a row of the error matrix of \(2\) columns.
In R (C++) code, given both the coefficient and error matrices:
Rcpp::cppFunction('arma::mat cppSim(arma::mat B, arma::mat E) {
int m = E.n_rows, n = E.n_cols;
arma::mat X(m, n);
X.row(0) = arma::zeros<arma::mat>(1, n);
for (int r = 1; r < m; r++) {
X.row(r) = X.row(r-1) * B + E.row(r);
}
return X;
}', depends="RcppArmadillo")
a <- matrix(c(0.5, 0.1, 0.1, 0.5), nrow = 2)
e <- matrix(rnorm(10000), ncol = 2)
rbenchmark::benchmark(cppSim(a, e), rSim(a, e), order="relative")[, 1:4]
># test replications elapsed relative
># 1 cppSim(a, e) 100 0.010 1.0
># 2 rSim(a, e) 100 0.728 72.8
#remotes::install_github("https://github.com/andrie/pagerank.git")
suppressMessages(library(utils))
library(pagerank)
cran <- "https://cloud.r-project.org"
pr <- compute_pagerank(cran)
round(100 * pr[1:5], 3)
># Rcpp ggplot2 dplyr MASS magrittr
># 2.744 1.516 1.274 1.122 0.814
db <- tools::CRAN_package_db() # added in R 3.4.0
db <- db[!duplicated(db[, 1]), ] # rows: number of packages
nTot <- nrow(db) # columns: different attributes
nRcpp <- length(tools::dependsOnPkgs("Rcpp", recursive = FALSE, installed = db))
nCompiled <- table(db[, "NeedsCompilation"])[["yes"]]
propRcpp <- nRcpp / nCompiled * 100
data.frame(tot = nTot, totRcpp = nRcpp, totCompiled = nCompiled,
RcppPctOfCompiled = propRcpp)
># tot totRcpp totCompiled RcppPctOfCompiled
># 1 23730 3127 5114 61.14587sourceCpp()Create standalone .cpp files with:
sourceCpp()
Consider a function defined as
\[ f(n) = \begin{cases} n & \text{when } n < 2 \\ f(n-1) + f(n-2) & \text{when } n \ge 2 \end{cases} \] that creates Fibonacci sequence. The R implementation and use:
#include <Rcpp.h>
using namespace Rcpp;
// This is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp
// function (or via the Source button on the editor toolbar). Learn
// more about Rcpp at:
//
// http://www.rcpp.org/
// http://adv-r.had.co.nz/Rcpp.html
// http://gallery.rcpp.org/
//
// [[Rcpp::export]]
int rec_fib_cpp(int n) {
if (n < 2) return(n);
return(rec_fib_cpp(n - 1) + rec_fib_cpp(n - 2));
}
// [[Rcpp::export]]
long long fib_cpp(int n) {
if (n <= 1) return n;
long long a = 0, b = 1, temp;
for (int i = 2; i <= n; ++i) {
temp = b;
b = a + b;
a = temp;
}
return b;
}
// You can include R code blocks in C++ files processed with sourceCpp
// (useful for testing and development). The R code will be automatically
// run after the compilation.
//
/*** R
all.equal(fib_cpp(15), fib_r(15), rec_fib_cpp(15), rec_fib_r(15))
*/library(rbenchmark)
benchmark(fib_cpp(25), fib_r(25), rec_fib_cpp(25), rec_fib_r(25))[, 1:4]
># test replications elapsed relative
># 1 fib_cpp(25) 100 0.00 NA
># 2 fib_r(25) 100 0.00 NA
># 3 rec_fib_cpp(25) 100 0.03 NA
># 4 rec_fib_r(25) 100 7.98 NA
library(microbenchmark)
microbenchmark(R = fib_r(47), Rcpp = fib_cpp(47), times = 100L)
># Unit: nanoseconds
># expr min lq mean median uq max neval
># R 2600 2700 3049 2700 2800 18500 100
># Rcpp 600 600 783 700 700 6500 100
microbenchmark(R = fib_r(92), Rcpp = fib_cpp(92), times = 100L)
># Unit: nanoseconds
># expr min lq mean median uq max neval
># R 3700 3800 4154 4000 4000 19900 100
># Rcpp 500 600 765 700 750 8000 100R vectors ↔︎ C++ classes:
NumericVector, IntegerVector, CharacterVector, LogicalVectorScalars: double, int, String, bool
Key methods:
.size(), .begin(), .end()NumericVector out(n)R Type mapping:
library(Rcpp)
cppFunction("NumericVector logabs(NumericVector x) {
return log(abs(x));
}")
logabs(seq(-5, 5, by = 2))
># [1] 1.609438 1.098612 0.000000 0.000000 1.098612 1.609438log(abs()) runs directly on vectors as R would.code/logabs2.cppNot vectorized but ‘sweeps’ f() along std::vector<double> via STL std::transform().
Add to package:
LinkingTo: Rcpp in DESCRIPTIONuseDynLib(pkg) & importFrom(Rcpp, sourceCpp) in NAMESPACEusethis::use_rcpp() automates setup
Run Rcpp::compileAttributes() to generate bindings
Thirteen Simple Steps Vignette by Dirk Eddelbuettel
