Jacob Myer
Jacob Myer

Reputation: 509

How should I vectorize this simple for loop in R?

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

Answers (1)

coffeinjunky
coffeinjunky

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:

Created in a loop:

set.seed(42)
n <- 10
x = numeric(n)

for (i in 1:n){
  x[i] <- rpois(1, 3) 
}

Created at once:

set.seed(42)
y <- rpois(n, 3) 

Check that the results are equal:

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

Related Questions