Optimizing R Code with Rcpp
Romain François
Consulting Datactive, ThinkR
Rcpp vectors
STL vectors
Vectorised R code
extract_positives <- function(x){
x[x>0]}
Inefficient code that grows a vector in a loop
extract_positives_loop <- function(x){
y <- numeric()
for( value in x){
if( value > 0 ){
y <- c(x, y)} }
y
}
NumericVector x ;
int n = x.size() ;
int np = 0 ;
for( int i=0 ; i<n ; i++ ){
if( ___ ){
np++ ;
}
}
NumericVector result(np) ;
for( int i=0, j=0 ; i<n ; i++ ){
if( ___ ){
result[j++] = x[i] ;
}
}
// [[Rcpp::export]]
std::vector<double> positives_stl( NumericVector x ){
std::vector<double> out ;
out.reserve( x.size() / 2 ) ;
for( ___ ; ___ ; ___ ){
if( ___ ){
out.push_back(___) ;
}
}
return out ;
}
Optimizing R Code with Rcpp