Optimizing R Code with Rcpp
Romain François
Consulting Datactive, ThinkR
// one number from a N(0,1)
double x = R::rnorm( 0, 1 ) ;
// one number from a U(-2,2)
double y = R::runif( -2, 2 ) ;
// ...
Random number generators in the Rcpp::
namespace.
NumericVector x = rnorm(10, 0, 2) ;
// same as this below
// because of using namespace Rcpp ;
//
// NumericVector x = Rcpp::rnorm(10, 0, 2) ;
Alternative using scalar versions from R::
// same as
NumericVector x(10) ;
for(int i=0; i<10; i++){
x[i] = R::rnorm(0, 2) ;
}
// we generate n numbers
NumericVector x(n) ;
// fill the vector in a loop
for( int i=0; i<n; i++){
// keep generating d until it gets positive
double d ;
do {
d = ... ;
} while( d < 0 ) ;
x[i] = d ;
}
int component( NumericVector weights, double total_weight ){
// return the index of the selected component}
NumericVector rmix( int n, NumericVector weights, NumericVector means,
NumericVector sds ){
NumericVector res(n) ;
for( int i=0; i<n; i++){
// find which component to use
...
// simulate using the mean and sd from the selected component
... }
return res ;
}
Optimizing R Code with Rcpp