[Rcpp-devel] Vectorized version of rbinom function via Rcpp

Douglas Bates bates at stat.wisc.edu
Thu Oct 25 18:30:33 CEST 2012


On Thu, Oct 25, 2012 at 9:29 AM, Dirk Eddelbuettel <edd at debian.org> wrote:
>
> Hi Carsten,
>
> On 25 October 2012 at 16:05, carsten Gerken wrote:
> | Hi All,
> |
> | I am trying to outsource the simulation of binomially distributed random
> | variables to C++ via Rcpp (e.g. to replicate the R command rbinom(10,10,c(1:10)
> | /20)). This works well as long as the third argument of the function (i.e. the
> | probability) is a single value and not a vector. I tried to compile the
> | following code:
> |
>
> [ Some editing here ]
>
>  rbinom_c <- rcpp( signature(n = "integer",m = "integer",p="numeric"), body="
>    int N = as<int>(n);
>    int M = as<int>(m);
>    NumericVector P = NumericVector(p);
>    NumericVector res = rbinom(N,M,P);
>    return res;
>  ")
>
> | But the compiler expects a “double” variable in the third argument.
>
> Correct, as I recall.  Some (common) things are vectors, some are scalars.
> As a simple example in rnorm(n, m, s) the mean m and stdev s are expected to
> be scalars.
>
> | Is there a
> | way of fixing the code without using an explicit loop in the C++ code?
>
> I don't think so. The code currently has this hard-wired:
>
>         inline NumericVector rbinom( int n, double nin, double pp ){
>                 return NumericVector( n, ::Rf_rbinom, nin, pp) ;
>         }
>
> so until one of us has sufficient to extend this (and test it) will have to
> do the loop at your end.

And I suggest that before expending a lot of effort on this you check
whether you are likely to do better than the R function rbinom.  That
R function is vectorized in C code and you are unlikely to make things
much faster by using Rcpp, unless you want to use the random variates
in another C++ function.


More information about the Rcpp-devel mailing list