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

Chris DuBois chris.dubois at gmail.com
Sun May 15 03:01:17 CEST 2011


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<http://www.cppreference.com/wiki/algorithm/accumulate>),
as the following works just fine:  std::accumulate( xx.begin(),
xx.end(),0.0,std::plus<double>())

Chris

On Sat, May 14, 2011 at 5:29 PM, Dirk Eddelbuettel <edd at debian.org> wrote:

>
> On 14 May 2011 at 17:13, Chris DuBois wrote:
> | Thanks Dirk.  Quick newbie followup question: Can we put functions within
> the
> | inline C++ code?  The following doesn't compile, for example:
> | src <- '
> | int addition (int a, int b)
> | {
> |   int r;
> |   r=a+b;
> |   return (r);
> | }
> | NumericVector xx(x);
> | return(xx);
> | '
> | testfun = cxxfunction(signature(x="numeric"),body=src,plugin="Rcpp")
>
> Use the 'verbose=TRUE' to cxxfunction() and it will become clear
> why -- a function is written around the 'body=...' argument,
> hence no chance that that part may contain another C++ function.
>
> The remedy is simple: use the "include=..." argument as in
>
>   inc <- '
>    int addition (int a, int b) {
>      int r = a + b;
>     return (r);
>   }
>   '
>
>   src = '
>    NumericVector xx(x);
>   return(xx);
>   '
>
>    testfun = cxxfunction(signature(x="numeric"), body=src, include=inc,
> plugin="Rcpp")
>
>
> That trick is used a couple of time in the documentation and examples.
>
>
> | On a related note, would you mind showing a quick working example using
> | std::accumulate?  The one below from the quick reference doesn't compile
> for
> | me.
>
>
> Try Google for something like that, eg a query that is restricted to my
> site as in
>
>    site:dirk.eddelbuettel.com  "std::accumulate"
>
> show five immediate hits.  You can similarly constrict the search
> to the rcpp-devel list.
>
> Can you send a small example for inline that shows how/where it quickref
> example fails for you?
>
> Dirk
>
> --
> Gauss once played himself in a zero-sum game and won $50.
>                      -- #11 at http://www.gaussfacts.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20110514/ed55ffb0/attachment.htm>


More information about the Rcpp-devel mailing list