在向量内的不同位置添加一系列元素

Bar*_*aby 5 r

我的目标是将多个元素插入到一个向量中,每个元素位于不同的位置。这是一个例子,后面是一些不起作用的试验。

w  <- c( 1,3,2,4,2,3,2,4,5,7,9,3,2,4,2,5,7,4,2 )
u  <- c( 3,7,9,12 )
o  <- c( 10 , 20 , 30 , 40 )
Run Code Online (Sandbox Code Playgroud)

我试过了:

append ( w , o , after = u )  

# which adds the series one time in the first location of after 

fun <- function (x) append ( w , o[[x]] , after = u[[x]] )
lapply ( seq ( length ( u )) , fun )

# which adds one element to the list each time for a new vector producing a  number of vectors 

for (i in length(o)) {
append ( w , o[[i]] , after = u[[i]] )
}
# which basically does nothing
Run Code Online (Sandbox Code Playgroud)

期望输出

1,3,2,10,4,2,3,2,20,4,5,30,7,9,3,40,2,4,2,5,7,4,2
Run Code Online (Sandbox Code Playgroud)

有没有办法在每个特定位置一次插入一个元素?我已经看到几个问题解决了单个元素的 append basic 问题,其中一个位置或两个元素要添加到同一位置,但不是多个元素要添加到向量中的多个位置。

jos*_*ber 3

您可以append通过计算每个新元素和旧元素的位置并一次性添加它们,以矢量化方式(也称为不重复 ing)来完成此操作:

# Positions of old and new elements
add.pos <- u + order(u)
old.pos <- seq_len(length(w) + length(u))
old.pos <- old.pos[!old.pos %in% add.pos]

# Construct new vector in one shot
new.vec <- rep(NA, length(old.pos))
new.vec[add.pos] <- o
new.vec[old.pos] <- w
new.vec
# [1]  1  3  2 10  4  2  3  2 20  4  5 30  7  9  3 40  2  4  2  5  7  4  2
Run Code Online (Sandbox Code Playgroud)

由于这不涉及每次添加元素时重复重新分配向量的空间,因此如果添加大量元素,它应该会更快。