Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

r - Alternate, interweave or interlace two vectors

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...