To interleave or interlace two vectors
I want to interleave two vectors of the same pattern and equal length Say:
a <- rpois(lambda=3,n=5e5) b <- rpois(lambda=4,n=5e5)
I want to interleave or interleave these two vectors to create an equivalent C (a [1], B [1], a [2], B [2],..., a [length], B [length)])
My first attempt was this:
sapply(X=rep.int(c(3,4),times=5e5),FUN=rpois,n=1)
But it takes rpois to be called more times than needed
So far, my best attempt is to convert it into a matrix and re convert it 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 do it? Or is there a function in base R to do the same thing?
Solution
Your rbind method should be very good You can also use
rpois(lambda=c(3,n=1e6)
Because r will automatically copy the vector of lambda value to the required length There is 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,rpois(5e+05,4))) 100 23.390 1.112168 # 1 rpois(1e+06,4)) 100 21.031 1.000000
Elegance is in the eyes of onlookers... Of course, the C (rbind (...)) method is generally used to build alternating vectors, while another solution is specific to rpois or other functions, like copying their parameters