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

Dirk Eddelbuettel edd at debian.org
Thu Oct 25 16:29:50 CEST 2012


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. 

As always, patches would be welcomed. :)

Dirk


-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com  


More information about the Rcpp-devel mailing list