Embedding Rcpp code in your R code
You can also write Rcpp code in your R code in 3 ways using sourceCpp()
cppFunction()
evalCpp()
respectively.
sourceCpp()
Save Rcpp code as string object in R and compile it with sourceCpp()
.
src <-
"#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double rcpp_sum(NumericVector v){
double sum = 0;
for(int i=0; i<v.length(); ++i){
sum += v[i];
}
return(sum);
}"
sourceCpp(code = src)
rcpp_sum(1:10)
cppFunction()
The cppFunction()
offers a handy way to create a single Rcpp function. You can omit #include <Rcpp.h>
and using namespase Rcpp;
when you use cppFunction()
.
src <-
"double rcpp_sum(NumericVector v){
double sum = 0;
for(int i=0; i<v.length(); ++i){
sum += v[i];
}
return(sum);
}
"
Rcpp::cppFunction(src)
rcpp_sum(1:10)
evalCpp()
You can evaluate a single C++ statement by using evalCpp()
.
# Showing maximum value of double.
evalCpp('std::numeric_limits<double>::max()')