Update -- I've implemented all of R's sample (with identical results) except for the walker alias method. I used Armadillo for ProbSampleReplace and ProbSampleNoReplace, since there's no good STL replacement for R's revsort. I'll submit a patch to RcppArmadillo when I get a chance. If anyone wants this in the meantime, I can email the source as a package that contains some example glue and unit tests.<br>
<br>best,<br>Christian<br><br><div class="gmail_quote">On Sat, Nov 3, 2012 at 4:52 AM, Christian Gunning <span dir="ltr"><<a href="mailto:xian@unm.edu" target="_blank">xian@unm.edu</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
Dear all,<br><br>Code for uniform sampling is below, following the prototype from earlier post. Results/unit-tests (not included) are identical to R-core sample().<br><br>-Christian<br><br><div>template <class T> <br>
T sample(const T &x, const unsigned int size, const bool replace ) {<br> int ii, jj;<br> int nOrig = x.size();<br> T ret(size);<br> if ( size > nOrig && !replace) throw std::range_error( "Tried to sample more elements than in x without replacement" ) ;<br>
IntegerVector index(size);<br> if (replace) {<br> SampleReplace(index, nOrig);<br> } else {<br> SampleNoReplace(index, nOrig);<br> }<br><br> for (ii=0; ii<size; ii++) {<br> jj = index[ii];<br>
ret[ii] = x[jj];<br> }<br> return(ret);<br>}<br><br>void SampleReplace( IntegerVector index, unsigned int nOrig) {<br> int ii;<br> int nSample = index.size();<br> for (ii = 0; ii < nSample; ii++) {<br>
index[ii] = nOrig * unif_rand();<br> }<br>}<br><br>void SampleNoReplace( IntegerVector index, unsigned int nOrig) {<br> int ii, jj;<br> int nSample = index.size();<br> IntegerVector sub(nOrig);<br> for (ii = 0; ii < nOrig; ii++) {<br>
sub[ii] = ii;<br> }<br><br> for (ii = 0; ii < nSample; ii++) {<br> jj = nOrig * unif_rand();<br> index[ii] = sub[jj];<br> // replace sampled element with last, decrement<br> sub[jj] = sub[--nOrig];<br>
}<br>}<br></div>
</blockquote></div><br><br clear="all"><br>-- <br>A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!<br>