Add a series of elements in different places inside the vector

I am trying to insert multiple elements into a vector each in different places. This is an example followed by a series of tests that do not work.

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 )

I tried:

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

Desired output

1,3,2,10,4,2,3,2,20,4,5,30,7,9,3,40,2,4,2,5,7,4,2

Is there a way to insert each item one at a time in a particular location? I saw several questions regarding the basic append element for one element with one location or two elements that should be added to the same position, but not for adding several elements to several locations in the vector.

+4
source share
4 answers

Here is another vector way to do it.

New <- rep(w, (1:2)[(1:length(w) %in% u) + 1])
New[u + 1:length(u)] <- o
New
# [1]  1  3  2 10  4  2  3  2 20  4  5 30  7  9  3 40  2  4  2  5  7  4  2

, u o

+4
x <- numeric(length(w)+length(o))
ind <- u + order(u) #index to insert o vector (which I shamelessly borrowed from Josilber answer)
x[ind] <- o
x[-ind] <- w
x
# [1]  1  3  2 10  4  2  3  2 20  4  5 30  7  9  3 40  2  4  2  5  7  4  2
+4

You can do this in vector form (aka not re- appending) by calculating the position of each new element and the old element and adding them to one shot:

# 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

Since this does not require multiple reallocation of space for the vector each time you add an element, it should be faster if you add a large number of elements.

+3
source
idx <- sort(c(1:length(w), u))
replace(w[idx], c(FALSE, diff(idx) == 0), o)
# [1]  1  3  2 10  4  2  3  2 20  4  5 30  7  9  3 40  2  4  2  5  7  4  2
+1
source

All Articles