Alternate, interweave or interlace two vectors

Viewed 4911

I want to interlace two vectors of same mode and equal length. Say:

a <- rpois(lambda=3,n=5e5)
b <- rpois(lambda=4,n=5e5)

I would like to interweave or interlace these two vectors, to create a vector that would be equivalently c(a[1],b[1],a[2],b[2],...,a[length(a)],b[length(b)])

My first attempt was this:

sapply(X=rep.int(c(3,4),times=5e5),FUN=rpois,n=1)

but it requires rpois to be called far more times than needed.

My best attempt so far has been to transform it into a matrix and reconvert back into a vector:

d <- c(rbind(rpois(lambda=3,n=5e5),rpois(lambda=4,n=5e5)))
d <- c(rbind(a,b))

Is there a better way to go about doing it? Or is there a function in base R that accomplishes the same thing?

2 Answers
Related