R
Rcpp
Feb 4, 2018     2 minutes read

1. What is Rcpp and why would you use it?

Or you can switch to Python. Or data.table. Or write it in C.

2. A “Hello World” example

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)

3. Using R’s numeric vector as input and output

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