Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert elements into multiple positions in a vector without iteration

Tags:

r

Given a vector u of elements and a vector i of indices into vector x, how can we insert the elements of u into x after the elements corresponding to the indices in i, without iteration?

For example

x <- c('a','b','c','d','e')
u <- c('X','X')
i <- c(2,3)
# now we want to get c('a','b','X','c','X','d','e')

I want to do this in one step (i.e. avoid loops) because each step requires the creation of a new vector, and in practice these are long vectors.

I'm hoping for some index magic.

like image 849
Museful Avatar asked Feb 09 '23 22:02

Museful


1 Answers

I think this should work as long as i does not contain duplicate indices.

idx <- sort(c(seq_along(x), i))
y <- x[idx]
y[duplicated(idx)] <- u
y
#[1] "a" "b" "X" "c" "X" "d" "e"

Edit As @MartinMorgan suggested in the comments, a much better way of doing this is c(x, u)[order(c(seq_along(x), i))].

like image 74
konvas Avatar answered Feb 11 '23 12:02

konvas