Jonathan Olmsted

Rcpp Updates: the sample function

| Comments

Two posts on the rcpp-gallery came out of some work I had to do using an accept-reject sampler. I came to the project after the sampler had already been implemented in R. Given the performance of the code as it was, the job was going to take too long, even on powerful machines. Trying some go-to R tricks didn’t result in enough of a performance boost, so I decided to implement in C++ using Rcpp

The sampler itself used R’s sample() function, so I went looking for the corresponding functionality in C++ (assuming Rcpp would have exposed it). And, while much of R’s random number generation is easily accessed, there was no clean way to hook into the C code underlying sample().

Christian Gunning addressed this by contributing a patch to RcppArmadillo which exposes much of the functionality of R’s sample(). We write about it here.

None of the examples in the above link really allow the Rcpp implementation to shine, so I put together an example accept-reject sampler that runs in C++-land thanks to Rcpp. You can see the results with fully working code here.

Altogether, you may not need to use Rcpp if all you want to do is call sample() once. But, if you have to repeatedly make calls to sample(), the code and the documentation exist for you to implement it readily in Rcpp.

Comments