将值附加到向量中的多个位置

时间:2018-05-02 16:39:33

标签: r

我们如何将单个值附加到向量中的多个位置?

x=c(1,2,3)
append(x, "a", c(1,3))
[1] "1" "a" "2" "3"

Warning messages:
1: In if (!after) c(values, x) else if (after >= lengx) c(x, values) else c(x[1L:after],  :
  條件的長度 > 1,因此只能用其第一元素
2: In if (after >= lengx) c(x, values) else c(x[1L:after], values,  :
  條件的長度 > 1,因此只能用其第一元素
3: In 1L:after : numerical expression has 2 elements: only the first used
4: In (after + 1L):lengx :
  numerical expression has 2 elements: only the first used

使用上面的代码,只有第一个位置被注册,并带有警告信息。

lapply(c(1,3), function(y) append(x, 'a', y))

得出这个结果:

[[1]]
[1] "1" "a" "2" "3"

[[2]]
[1] "1" "2" "3" "a"

预期输出:

1 a 2 3 a

1 个答案:

答案 0 :(得分:2)

您可以使用`Reduce function:

x=1:10
pos=c(3,5,7,10)
Reduce(function(i,j)append(i,"a",j),cumsum(c(pos[1],diff(pos)+1)),init=x)
[1] "1"  "2"  "3"  "a"  "4"  "5"  "a"  "6"  "7"  "a"  "8"  "9"  "10" "a"