Alternate, interweave or interlace two vectors

Your rbind method should work well. You could also use

rpois(lambda=c(3,4),n=1e6)

because R will automatically replicate the vector of lambda values to the required length. There’s not much difference in speed:

library(rbenchmark)
benchmark(rpois(1e6,c(3,4)),
     c(rbind(rpois(5e5,3),rpois(5e5,4))))


#                                        test replications elapsed relative
# 2 c(rbind(rpois(5e+05, 3), rpois(5e+05, 4)))          100  23.390 1.112168
# 1                      rpois(1e+06, c(3, 4))          100  21.031 1.000000

and elegance is in the eye of the beholder … of course, the c(rbind(...)) method works in general for constructing alternating vectors, while the other solution is specific to rpois or other functions that replicate their arguments in that way.

Leave a Comment