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.
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))]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With