Rcpp

Over the years, R has offered two main ways to interface R to C/C++, via the .C() and .Call() functions. You generate a dynamic load library from the C/C++ code, say containing a functions f(), then load it into R using dyn.load() and finally call f() from one of the above two interfaces.

The .Call() function is the more sophisticated of the two, with better efficiency and generality. However, to use it one must know the internals of R, in the so-called SEXPs ("S expressions"), which are complex.

The Rcpp package enables the programmer to attain the power of .Call() while being actually easier than .C(). In essence, Rcpp allows you to use R objects from within C.

Get a brief introduction to Rcpp in this excerpt from my forthcoming book on parallel computation.

At the (slightly) more advanced level, there is Rcpp Syntactic Sugar. In addition to C/C++ code being able to work with R objects, Sugar allows us to work with R vectorized operations. Here's an example from the Rcpp package. Say our original code is (with my comments added)

// input 2 R vectors, transform into an output vector, consisting of
// squares or negative squares of the inputs
RcppExport SEXP foo( SEXP x, SEXP y) {
   // make C/C++ pointers to x, y
   Rcpp::NumericVector xx(x), yy(y);
   // determine length of x
   int n = xx.size();
   // allocate space for the output vector
   Rcpp::NumericVector res(n) ;
   // straightforward computation
   double x_ = 0.0, y_ = 0.0 ;
   for( int i=0; i

Here it is with Rcpp Sugar:

RcppExport SEXP foo( SEXP xs, SEXP ys){
   Rcpp::NumericVector x(xs);
   Rcpp::NumericVector y(ys);
   return Rcpp::wrap(ifelse( x < y, x*x, -(y*y)));
}

All this through the magic of C++ operator overloading!

More examples in the Rcpp Gallery.