假设我有一个像这样的 vector :
vector <- 1:9
#$ [1] 1 2 3 4 5 6 7 8 9
我现在想将每个
i
重复到i+x
序列n
次,就像x=3
和n=2
一样:#$ [1] 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9
我是这样实现的:
index <- NULL
x <- 3
n <- 2
for (i in 1:(length(vector)/3)) {
index <- c(index, rep(c(1:x + (i-1)*x), n))
}
#$ [1] 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9
这很好用,但是我有一种直觉,那就是必须有一个更好的方法(特别是因为通常,for循环不是答案)。
附言:这种情况的用例实际上是在数据帧中重复行,但是仅获取索引 vector 就可以了。
最佳答案
您可以尝试先对 vector 进行split
,然后使用rep
和unlist
:
x <- 3 # this is the length of each subset sequence from i to i+x (see above)
n <- 2 # this is how many times you want to repeat each subset sequence
unlist(lapply(split(vector, rep(1:(length(vector)/x), each = x)), rep, n), use.names = FALSE)
# [1] 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9
或者,您可以尝试创建
matrix
并将其转换为 vector :c(do.call(rbind, replicate(n, matrix(vector, ncol = x), FALSE)))
# [1] 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9