[Rcpp-devel] Rcpp equivalent of sample()?

Dirk Eddelbuettel edd at debian.org
Sun May 15 03:19:16 CEST 2011

On 14 May 2011 at 18:01, Chris DuBois wrote:
| Thanks Dirk.  Passing the addition function in the includes argument worked
| great.  
| Also, one of the links from your suggested Google search led me to this
| (working) example for std::accumulate:
| src <- 'NumericVector xx(x);
| return wrap( std::accumulate( xx.begin(), xx.end(), 0.0));'
| fx <- cxxfunction(signature( x = "numeric" ),body=src,plugin = "Rcpp")
| fx(1:10)  # 55
| I had been copying the quickref and using:  std::accumulate( xx.begin(),
| xx.end(),std::plus<double>(),0.0)
| I think this might be a typo where the last two arguments are transposed (which
| I shouldn't have noticed after browsing the function's c++ reference), as the
| following works just fine:  std::accumulate( xx.begin(), xx.end
| (),0.0,std::plus<double>())

Good catch.  The arguments are

     start, end, intial value, (optional) operator function

and std::plus<double>() is the default for summation. So that was an error,
and hence a Thank You! for catching it.  I just committed this new section:

\paragraph{STL interface}~
// sum a vector from beginning to end
double s = std::accumulate(x.begin(),
   x.end(), 0.0);
// prod of elements from beginning to end
int p = std::accumulate(vec.begin(),
    vec.end(), 1, std::multiplies<int>());
// inner_product to compute sum of squares
double s2 = std::inner_product(res.begin(),
    res.end(), res.begin(), 0.0);

which shows std::multiplies<int>() as an alternative operator for accumulate
as well as inner_product for a sum-of-squares computation (as once suggested
by Doug).


Gauss once played himself in a zero-sum game and won $50.
                      -- #11 at http://www.gaussfacts.com

More information about the Rcpp-devel mailing list