Random number generation

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

Generating single random numbers

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

// ...
Optimizing R Code with Rcpp

Generating vectors

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) ;
}
Optimizing R Code with Rcpp

Optimizing R Code with Rcpp

Rejection sampling

// 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 ;    
}
Optimizing R Code with Rcpp

Optimizing R Code with Rcpp
  • Choose the component of the mixture using the weights
int component( NumericVector weights, double total_weight ){
    // return the index of the selected component}
  • Generate the number using the parameters of the selected components
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

Let's practice!

Optimizing R Code with Rcpp

Preparing Video For Download...