[英]What is an expressive and efficient way to vectorize seq in R
I am aware of seq, which used in this way: 我知道seq,它以这种方式使用:
seq(by=1, to=3, by=1)
will get you from c(1) to 会让你从c(1)到
c(1,2,3) C(1,2,3)
How can I vectorize this behavior to go from 如何将此行为矢量化为来自
Input: 输入:
c(1,1,1)
Output: 输出:
c(1,1,1,2,2,2,3,3,3)
seq
isn't vectorised. seq
没有矢量化。 You could use one of the loops to get the same behavior. 您可以使用其中一个循环来获得相同的行为。
For example, with mapply
例如,与mapply
x <- c(1,1,1)
c(t(mapply(seq, x, 3)))
#[1] 1 1 1 2 2 2 3 3 3
If you want every sequence go till length(x)
use that instead of hard-coded 3. 如果你想要每个序列直到length(x)
使用它而不是硬编码3。
Besides, if your x
will always start with 1 as shown in the example you can use rep
and sequence
此外,如果您的x
始终以1开头,如示例所示,您可以使用rep
和sequence
sort(sequence(rep(length(x), length(x))))
#[1] 1 1 1 2 2 2 3 3 3
An option is rep
and it is vectorized. 一个选项是rep
,它是矢量化的。 No need to use loops 无需使用循环
rep(seq_along(v1), each = length(v1))
#[1] 1 1 1 2 2 2 3 3 3
Or another option is replicate
或者另一种选择是replicate
c(t(replicate(3, seq(1, 3, 1))))
#[1] 1 1 1 2 2 2 3 3 3
If we wanted to vectorize the seq
, use Vectorize
如果我们想要对seq
进行矢量化,请使用Vectorize
c(t(Vectorize(function(x) seq(x, 3, 1))(v1)))
#[1] 1 1 1 2 2 2 3 3 3
v1 <- c(1, 1, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.