-2

I want to vectorize the way I draw. Suppose I have a vector of parameter values for poisson, and for each parameter, I want to draw 1 sample. Is there a way to do this without looping?

wolfsatthedoor
  • 7,163
  • 18
  • 46
  • 90

1 Answers1

2

You need to specify vectors for each function argument in order to obtain a vector result:

> rpois(rep(1,4), lambda = c(1,10,100,1000))
[1]    0   12   88 1031

Regarding the first argument, see the documentation:

The length of the result is determined by n for rpois, and is the maximum of the lengths of the numerical parameters for the other functions.

The numerical parameters other than n are recycled to the length of the result. Only the first elements of the logical parameters are used.

If you need multiple draws at each level, then you'll have to mapply (or Vectorize) the function:

> mapply(rpois, rep(4,4), lambda = c(1,10,100,1000))
     [,1] [,2] [,3] [,4]
[1,]    0    8   78 1016
[2,]    0   10  106 1044
[3,]    1   14   97 1004
[4,]    0   13   94  983
Community
  • 1
  • 1
Thomas
  • 43,637
  • 12
  • 109
  • 140