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?
Asked
Active
Viewed 40 times
-2
-
`rpois` is vectorized already. – Thomas Apr 23 '14 at 21:31
-
How do you do that? rpois(1,vector)? That does not draw 1 for each element in vector. – wolfsatthedoor Apr 23 '14 at 21:32
-
Reading `?rpois` might help answer that. – Rich Scriven Apr 23 '14 at 21:33
-
I did, couldnt figure it out. – wolfsatthedoor Apr 23 '14 at 21:34
1 Answers
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
-
What is the rep doing? When you do rep(111111,4),.. it gives the same result. Thank you for your help. – wolfsatthedoor Apr 23 '14 at 21:39
-
`mapply/Map` will recycle arguments where necessary. `Map(rpois, 4, c(1,10,100,1000) )` will cut the mustard. – thelatemail Apr 24 '14 at 01:08