Vectors from the STL

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

Rcpp vectors vs STL vectors

Rcpp vectors

  • Thin wrappers around R vectors
  • Cannot (cost effectively) change size: data copy every time

STL vectors

  • Independent of R vectors
  • Cheap to grow and shrink: amortized copies
Optimizing R Code with Rcpp

Extract positives values from a vector

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
}
Optimizing R Code with Rcpp

Extract positive values: alternative algorithm

  • First 🔃 to count the final size
NumericVector x ; 
int n = x.size() ;
int np = 0 ;
for( int i=0 ; i<n ; i++ ){ 
    if( ___ ){
        np++ ;
    }
}
Optimizing R Code with Rcpp

Extract positive values: alternative algorithm

  • Create a vector of the right size
NumericVector result(np) ;
  • Second 🔃 to fill the vector
for( int i=0, j=0 ; i<n ; i++ ){
    if( ___ ){
        result[j++] = x[i] ;
    }
}
Optimizing R Code with Rcpp

Simpler algorithm using the STL

// [[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

Let's practice!

Optimizing R Code with Rcpp

Preparing Video For Download...