Optimizing R Code with Rcpp
Romain François
Consulting Datactive, ThinkR
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
// [[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
// [[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].
// [[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
double value = 42.0 ;
int n = 20 ;
// create a numeric vector of size 20
// with all values set to 42
NumericVector x( n, value ) ;
NumericVector x = NumericVector::create( 1, 2, 3 );
CharacterVector s = CharacterVector::create( "pink", "blue" );
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
) ;
// [[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