Optimizing R Code with Rcpp
Romain François
Consulting Datactive, ThinkR
evalCpp()
evalCpp( "40 + 2" )
42
cppFunction()
cppFunction( "int fun(){ return 42; }")
fun()
42
C++ code in code.cpp
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
int timesTwo( int x ){
return 2*x ;
}
The sourceCpp()
function compiles and loads it
library(Rcpp)
sourceCpp( "code.cpp" )
timesTwo( 21 )
42
#include <Rcpp.h>
_____ _________ ____ _
__ ________________
___ _________ ___ _ __
______ ___ _
_
Include only Rcpp.h
#include <Rcpp.h>
using namespace Rcpp ;
__ ________________
___ _________ ___ _ __
______ ___ _
_
Something
instead of Rcpp::Something
, when Something
is in Rcpp
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
___ _________ ___ _ __
______ ___ _
_
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
int timesTwo( int x ){
return 2*x ;
}
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
int timesTwo( int x ){
return 2*x ;}
load the function into R
library(Rcpp)
sourceCpp( "code.cpp" )
Call it, just as any other R function.
timesTwo( 21 )
42
Optimizing R Code with Rcpp