Optimizing R Code with Rcpp
Romain François
Consulting Datactive, ThinkR
Rcpp vector classes:
NumericVector to manipulate numeric vectors, e.g. c(1,2,3)IntegerVector for integer e.g. 1:3LogicalVector for logical e.g. c(TRUE, FALSE)CharacterVector for strings e.g. c("a", "b", "c")Also:
List for lists, aka vectors of arbitrary R objectsMost important methods:
x.size() gives the number of elements of the vector xx[i] gives the element on the ith position in the vector xIndexing in C++ starts at 0. The index is an offset to the first position.
// first element of the vector
x[0]
// last element
x[x.size()-1]
Indexing in R starts at 1.
# first
x[1]
# last
x[length(x)]

// x comes from somewhere else (patience ...)
NumericVector x = ... ;
double value = x[0] ;
x[0] = 12.0 ;
// x comes from somewhere else (patience ...)
NumericVector x = ... ;
int n = x.size() ;
double value = x[n-1] ;
x[n-1] = 12.0 ;
// x comes from somewhere
NumericVector x = ... ;
int n = x.size() ;
for( int i=0; i<n; i++){
// manipulate x[i]
}
Optimizing R Code with Rcpp