STL random_sample

December 31, 2012

(This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers)

An earlier post looked at random shuffle for permutations. The STL also supports creation of random samples.

Alas, it seems that this functionality has not been promoted to the C++ standard yet — so we will have to do with what is an extensions by the GNU g++ compiler.

The other drawback is the sampling without replacement.

As in the previous post, we use a function object conformant to the STL’s requirements for a random number generator to be able to use R’s RNG.


// wrapper around R's RNG such that we get a uniform distribution over
// [0,n) as required by the STL algorithm
inline int randWrapper(const int n) { return floor(unif_rand()*n); }

// it would appear that randomSample is still only a GNU g++ extension ?

// [[Rcpp::export]]
Rcpp::NumericVector randomSample(Rcpp::NumericVector a, int n) {
    // clone a into b to leave a alone
    Rcpp::NumericVector b(n);
    __gnu_cxx::random_sample(a.begin(), a.end(), 
                             b.begin(), b.end(), randWrapper);
    return b;

We can illustrate this on a simple example:

a <- 1:8
randomSample(a, 4)
[1] 1 2 7 4
randomSample(a, 4)
[1] 1 2 7 4

To leave a comment for the author, please follow the link and comment on their blog: Rcpp Gallery. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)