Optimizing R Code with Rcpp
Romain François
Consulting Datactive, ThinkR
evalCpp( "40+2" )
42
cppFunction( "double add( double x, double y){
return x + y ;
}")
add( 40, 2 )
42
for( init ; condition ; increment ){
body
}
init
: what happens at the beginningcondition
: should the loop continueincrement
: after each iterationbody
: what the loop doesfor( int i=0; i<n; i++){
// do something with i
}
NumericVector x = ... ;
int n = x.size() ;
// first value
x[0]
// second value
x[1]
// last value
x[n-1]
#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;
}
#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