交替、交织或交织两个向量 [英] 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)
我想交织或交错这两个向量,以创建一个等效的向量 c(a[1],b[1],a[2],b[2],...,a[length(a)],b[length(b)])
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)
但它要求 rpois
被调用的次数远远超过需要的次数.
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))
有没有更好的方法来做这件事?或者在基础 R
中是否有一个函数可以完成同样的事情?
Is there a better way to go about doing it? Or is there a function in base R
that accomplishes the same thing?
推荐答案
您的 rbind
方法应该可以正常工作.你也可以使用
Your rbind
method should work well. You could also use
rpois(lambda=c(3,4),n=1e6)
因为 R 会自动将 lambda 值的向量复制到所需的长度.速度差别不大:
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
优雅在旁观者的眼中......当然,c(rbind(...))
方法通常适用于构造交替向量,而另一种解决方案是特定的rpois
或其他以这种方式复制其参数的函数.
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.
这篇关于交替、交织或交织两个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!