Creating vectors

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

Get a vector from the R side

C++ code

// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}

Called from R

x <- c(13.2, 34.1)
extract(x, 0)

x[1]
13.2

13.2
Optimizing R Code with Rcpp
// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}

Several cases

# x is already a numeric vector
extract( c(13.3, 54.2), 0 )
13.3
# x is an integer vector, it is first coerced to a numeric vector
extract( 1:10, 0 )
1
Optimizing R Code with Rcpp
// [[Rcpp::export]]
double extract( NumericVector x, int i){
    return x[i] ;}
# conversion not possible: error
extract( letters, 0 )
Error in extract(letters, 0) : 
  Not compatible with requested type: [type=character; target=double].
Optimizing R Code with Rcpp

Create a vector of a given size

// [[Rcpp::export]]
NumericVector ones(int n){
    // create a new numeric vector of size n
    NumericVector x(n) ;    
    // manipulate it
    for( int i=0; i<n; i++){
        x[i] = 1 ; }
    return x ;
}

Calling ones from R:

ones(10)
1 1 1 1 1 1 1 1 1 1
Optimizing R Code with Rcpp

Constructor variants

double value = 42.0 ;
int n = 20 ;

// create a numeric vector of size 20 
// with all values set to 42
NumericVector x( n, value ) ;

Optimizing R Code with Rcpp

Given set of values

NumericVector x = NumericVector::create( 1, 2, 3 );

CharacterVector s = CharacterVector::create( "pink", "blue" );
Optimizing R Code with Rcpp

Given set of values with names

Naming all values

NumericVector x = NumericVector::create( 
    _["a"] = 1, _["b"] = 2, _["c"] = 3
) ;

Only naming some values

IntegerVector y = IntegerVector::create( 
    _["d"] = 4, 5, 6, _["f"] = 7
) ;
Optimizing R Code with Rcpp

Vector cloning

// [[Rcpp::export]]
NumericVector positives( NumericVector x ){

    // clone x into y
    NumericVector y = clone(x) ;

    for( int i=0; i< y.size(); i++){
        if( y[i] < 0 ) y[i] = 0 ;
    }
    return y ;
}
Optimizing R Code with Rcpp

Let's practice!

Optimizing R Code with Rcpp

Preparing Video For Download...