data science tutorials and snippets prepared by tomis9
Rcpp
is a R library which let’s you embed C++ code inside your R program.
Useful when you have a bottleneck in your code which makes the execution last forever. In that case you can rewrite in into super-fast C++.
Or you can switch to Python. Or data.table. Or write it in C.
Example taken from Avanced R by Hadley Wickam (link).
library(Rcpp)
So far so good. This is how we create a C++ function add
:
cppFunction('int add(int x, int y, int z) {
int sum = x + y + z;
return sum;
}')
and invoke it:
add(1, 2, 3)
## [1] 6
You can check that this actually is a C++ function simply by:
add
## function (x, y, z)
## .Call(<pointer: 0x7f323c9af220>, x, y, z)
A slighlty more complicated function, which calculates a distance between a value and a vector of values:
cppFunction('NumericVector pdistC(double x, NumericVector ys) {
int n = ys.size();
NumericVector out(n);
for(int i = 0; i < n; ++i) {
out[i] = sqrt(pow(ys[i] - x, 2.0));
}
return out;
}')
And let’s run this function:
pdistC(10, c(11, -12, 30))
## [1] 1 22 20