[英]Insert elements into a vector at a given position, a given number of times
I have vector x <- c(1:50)
, and I want to insert y <- c(1,2)
every 10nth position 5 times. 我有向量
x <- c(1:50)
,我想每隔10个位置插入y <- c(1,2)
5次。
x <- c(1:50)
y <- c(1,2)
z <- c(seq(10,50,10))
The product has to be like this: 该产品必须是这样的:
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
I have tried with append, but it doesn't use "times"... 我尝试过追加,但它不使用“时代”......
We can split
the 'x' into a list
of vector
based on a grouping index created with %/%``, concatenate (
c ) with the 'y' using 'Map
and unlist
the list
to get the vector
我们可以
split
的“X”到list
的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
You can use append if you use a loop ala How to insert elements into a vector? 如果使用循环ala,可以使用append 如何将元素插入向量?
x <- 1:50
y <- c(1,2)
z <- c(seq(10,50,10))
for(i in 0:(length(z)-1)) {
out <- append(x, y, after=(z[i+1]+i))
}
out
But I like akrun's suggestion 但我喜欢阿克伦的建议
A simple solution is obtained by transforming x into a 10X5 matrix and then incrementally rbind
ing 1 and 2. c
is used to return a vector. 一个简单的解决方案是通过将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
This can be generalize to more than 2 values by putting them in a list and using Reduce
: 通过将它们放入列表并使用
Reduce
可以将其推广到2个以上的值:
c(Reduce(rbind, list(matrix(x, 10), 1, 2)))
Following @akrun's comment, you can use y in place a 1,2 in the line above with 按照@ akrun的评论,您可以在上面的行中使用y代替1,2
c(Reduce(rbind, append(list(matrix(x, 10)), y)))
or 要么
c(Reduce(rbind, c(list(matrix(x, 10)), as.list(y))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.