Source your C++ code
Source stand-alone C++ files into R using sourceCpp()
C++ files have extension .cpp
#include <Rcpp.h>
using namespace Rcpp;
And for each function that you want available within R, you need to prefix it with:
// [[Rcpp::export]]
Inside a cpp file you can include R
code using special comments
/*** R
rcode here
*/
Example
This block in Rmarkdown uses {Rcpp}
as a short hand for engine = “Rcpp”.
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double meanC(NumericVector x) {
int n = x.size();
double total = 0;
for(int i = 0; i < n; ++i) {
total += x[i];
}
return total / n;
}
/*** R
x <- runif(1e5)
bench::mark(
mean(x),
meanC(x)
)
*/
NOTE: For some reason although the r code above runs, knit
doesn’t include the output. Why?