To test our compiler and make sure that Rcpp is installed, execute the following to run and compile a short Rcpp snippet
library("Rcpp")
evalCpp("2 + 2")
## [1] 4
The above code, although seemingly short, is in fact doing a whole lot in the background. This call to evalCpp
is taking the passed in string, constructing the necessary boilerplate code for a minimal C++ program, then compiling and executing the resulting program.
It’s also possible to compile a string into a function that is then accessible to you in R
library("Rcpp")
cppFunction("
bool is_odd_cpp(int num = 10) {
bool result = (num % 2 == 1);
return result;
}
")
is_odd_cpp(42L)
## [1] FALSE
One of the primary reasons to use Rcpp is for gains in speed as we’re working at a lower abstraction level. Let’s see how this cpp function compares to the R version
library(microbenchmark)
is_odd_r <- function(num = 10L) {
result <- (num %% 2L == 1L)
return(result)
}
results <- microbenchmark(
is_odd_r = is_odd_r(12L),
is_odd_cpp = is_odd_cpp(12L)
)
results
## Unit: nanoseconds
## expr min lq mean median uq max neval cld
## is_odd_r 310 358 22917.39 515 632.5 2230425 100 a
## is_odd_cpp 964 1209 12875.92 1663 3204.0 1060537 100 a
The C++ version of is_odd
is about twice as fast as the R version.
It’s easy to see, though, that this is inline usage of strings is not a scalable way of writing complex C++ code to be called from R. Luckily, Rcpp works very well using the original C++ file format .cpp