[R] sapply function and poisson distribution

peter dalgaard pdalgd at gmail.com
Mon Jan 5 11:29:19 CET 2015


On 05 Jan 2015, at 00:21 , Pete Brecknock <Peter.Brecknock at bp.com> wrote:

> n <- c(1,2,3,4,5)
> lambda <- c(0.1,0.8,1.2,2.2,4.2)
> 
> mapply(function(x,y) rpois(x,y), n, lambda)  


Yes. I'd throw in a SIMPLIFY=FALSE to avoid getting results in a different format if n is constant (then again, sapply() in the original question is sort of asking for that kind of trouble...).

An alternative is to use the fact that rpois() vectorizes on the lambda argument:

ll <- rep(lambda, n)
g <- rep(seq_along(lambda), n)
N <- sum(n)
split(rpois(N, ll), g)

which can of course equally well be wrapped in a function as Pete's solution can.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list