Rcpp classes and vectors

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

Previously on this course

  • Create C++ functions ✅
  • Write loops ✅
Optimizing R Code with Rcpp

Vector classes

Rcpp vector classes:

  • NumericVector to manipulate numeric vectors, e.g. c(1,2,3)
  • IntegerVector for integer e.g. 1:3
  • LogicalVector 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 objects
Optimizing R Code with Rcpp

Vector classes api

Most important methods:

  • x.size() gives the number of elements of the vector x
  • x[i] gives the element on the ith position in the vector x
Optimizing R Code with Rcpp

C++ indexing

Indexing 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)]
Optimizing R Code with Rcpp

Optimizing R Code with Rcpp

The first element of a vector

// x comes from somewhere else (patience ...)
NumericVector x = ... ; 

double value = x[0] ;

x[0] = 12.0 ;
Optimizing R Code with Rcpp

The last element of a vector

// x comes from somewhere else (patience ...)
NumericVector x = ... ; 
int n = x.size() ;

double value = x[n-1] ;

x[n-1] = 12.0 ;
Optimizing R Code with Rcpp

Looping around a vector

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

Let's practice!

Optimizing R Code with Rcpp

Preparing Video For Download...