[Rcpp-devel] Sample function(s) for inclusion in RcppArmadillo

Romain Francois romain at r-enthusiasts.com
Wed Nov 14 14:16:59 CET 2012


Le 14/11/12 14:05, Christian Gunning a écrit :
> Dear all,
>
> The attached file is for inclusion in RcppArmadillo/src.  It's a
> templated implementation of R's sample that relies on a few Armadillo
> functions.  It should produce results identical to R, except when R uses
> Walker's alias method (with replacement, more than 200 nonzero
> probabilities given).
>
> This is intended to be used solely in C++ code, and is not exported.
>
> best,
> Christian
> University of New Mexico
>
> --
> A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!

Interesting. With some more work, we could even make this sugary. i.e. 
have this signature:

template <int RTYPE, bool NA, typename T>
Rcpp::Vector<RTYPE> sample(const Rcpp::VectorBase<RTYPE,NA,T> &x, const 
int size, const bool replace, NumericVector prob_ = NumericVector(0) ) {

	typedef Rcpp::Vector<RTYPE> TARGET ;
	// Templated sample -- should work on any Rcpp Vector
     int ii, jj;
     int nOrig = x.size();
     int probsize = prob_.size();
     // Create return object
     TARGET ret(size);
	if ( size > nOrig && !replace) throw std::range_error( "Tried to sample 
more elements than in x without replacement" ) ;
	
     ...

}

So that we could sample sugar expressions :-)

Romain

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30

R Graph Gallery: http://gallery.r-enthusiasts.com
`- http://bit.ly/SweN1Z : SuperStorm Sandy

blog:            http://romainfrancois.blog.free.fr
|- http://bit.ly/RE6sYH : OOP with Rcpp modules
`- http://bit.ly/Thw7IK : Rcpp modules more flexible



More information about the Rcpp-devel mailing list