Congratulations!

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

evalCpp and cppFunction

  • Evaluating simple C++ statements
evalCpp( "40+2" )
42
  • Creating a C++ function from the R console
cppFunction( "double add( double x, double y){
    return x + y ;
}")
add( 40, 2 )
42
Optimizing R Code with Rcpp

For loops

for( init ; condition ; increment ){
    body
}
  • init: what happens at the beginning
  • condition: should the loop continue
  • increment: after each iteration
  • body: what the loop does
Optimizing R Code with Rcpp

For loops

for( int i=0; i<n; i++){
    // do something with i
}
Optimizing R Code with Rcpp

Vector indexing

NumericVector x = ... ; 
int n = x.size() ;
// first value
x[0]
// second value
x[1]
// last value
x[n-1]
Optimizing R Code with Rcpp

C++ files with Rcpp

#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
double add( double x, double y){
    return x + y ;
}
// [[Rcpp::export]]
double twice( double x){
    return 2.0 * x;
}
Optimizing R Code with Rcpp

Typical Rcpp function

#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
double fun( NumericVector x ){

    // extract data from input and prepare outputs
    int n = x.size() ;
    double res = 0.0 ;

    // loop around input and/or output
    for(int i=0; i<n; i++){
        // do something with x[i]
    }

    // return output
    return res ;
}
Optimizing R Code with Rcpp

Congratulations!

Optimizing R Code with Rcpp

Preparing Video For Download...