Rcpp features two functions that enable code compilation inline and exportation directly into R: cppFunction()
and evalCpp()
. A third function called sourceCpp()
exists to read in C++ code in a separate file though can be used akin to cppFunction()
.
Below is an example of compiling a C++ function within R. Note the use of ""
to surround the source.
# Note - This is R code.
# cppFunction in Rcpp allows for rapid testing.
require(Rcpp)
# Creates a function that multiples each element in a vector
# Returns the modified vector.
cppFunction("
NumericVector exfun(NumericVector x, int i){
x = x*i;
return x;
}")
# Calling function in R
exfun(1:5, 3)
To quickly understand a C++ expression use:
# Use evalCpp to evaluate C++ expressions
evalCpp("std::numeric_limits<double>::max()")
## [1] 1.797693e+308