Reputation: 509
The loop to be vectorized:
n = 1000000
x = numeric(n)
for (I in 1:n) x[i] = rpois(1, 3) + rpois(1, 5)
The original is just too slow, I don't have much experience with for loops or the apply family of functions yet so I think I would just need to see an example of how this could be done and I would understand. Thanks
Upvotes: 1
Views: 123
Reputation: 11514
Try
x = rpois(n, 3) + rpois(n, 5)
rpois(n,3)
already creates many draws, so there is no need to loop.
To see this, note the following:
set.seed(42)
n <- 10
x = numeric(n)
for (i in 1:n){
x[i] <- rpois(1, 3)
}
set.seed(42)
y <- rpois(n, 3)
all.equal(x,y)
[1] TRUE
Note that the results of the addition will be slightly different from each other since the increments in the random number generator will differ, but that is a minor detail. The point is there is no need for a loop.
Upvotes: 4