# STL random_sample

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**Rcpp Gallery**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

#include <Rcpp.h> // 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 ? #include <ext/algorithm> // [[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 set.seed(42) randomSample(a, 4) [1] 1 2 7 4 set.seed(42) 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**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.