我有向量x <- c(1:50)
,我想每隔10个位置插入y <- c(1,2)
5次。
x <- c(1:50)
y <- c(1,2)
z <- c(seq(10,50,10))
产品必须是这样的:
1 2 3 4 5 6 7 8 9 10 1 2 11 12 13 14 15 16 17 18 19 20 1 2 21 22 23 24 25 26 27 28 29 30 1 2 31 32 33 34 35 36 37 38 39 40 1 2 41 42 43 44 45 46 47 48 49 50 1 2
我尝试过追加,但它没有使用“次”......
答案 0 :(得分:6)
我们可以split
&#39; x&#39;根据使用list
c vector
创建的分组索引和%/%``, concatenate (
) with the 'y' using 'Map
获取unlist
list
vector
}
unlist(Map(c, split(x, (x-1)%/%10), list(y)), use.names = FALSE)
#[1] 1 2 3 4 5 6 7 8 9 10 1 2 11 12 13 14 15 16 17 18 19 20 1 2 21
#[26] 22 23 24 25 26 27 28 29 30 1 2 31 32 33 34 35 36 37 38 39 40 1 2 41 42
#[51] 43 44 45 46 47 48 49 50 1 2
答案 1 :(得分:4)
如果您使用循环ala How to insert elements into a vector?
,则可以使用追加<ul class="true">
</ul>
<ul class="false">
</ul>
<ul id="true"></ul>
<ul id="false"></ul>
但我喜欢akrun的建议
答案 2 :(得分:2)
通过将x转换为10X5矩阵然后递增rbind
1和2来获得简单的解决方案。c
用于返回向量。
c(rbind(rbind(matrix(x, 10), 1), 2))
[1] 1 2 3 4 5 6 7 8 9 10 1 2 11 12 13 14 15 16 17 18 19 20 1 2 21 22 23 24
[29] 25 26 27 28 29 30 1 2 31 32 33 34 35 36 37 38 39 40 1 2 41 42 43 44 45 46 47 48
[57] 49 50 1 2
这可以通过将它们放在列表中并使用Reduce
来推广到2个以上的值:
c(Reduce(rbind, list(matrix(x, 10), 1, 2)))
按照@ akrun的评论,您可以在上面的行中使用y替换
c(Reduce(rbind, append(list(matrix(x, 10)), y)))
或
c(Reduce(rbind, c(list(matrix(x, 10)), as.list(y))))