How to insert elements at several positions in a vector without iteration

For a vector of uelements and a vector of iindices in a vector x, how can we insert elements uin xafter the elements corresponding to indices in i, without iterations?

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 hope for the magic of the index.

+4
source share
3 answers

I think this should work as long as it idoes not contain duplicate indexes.

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 suggested by @MartinMorgan in the comments, a much better way to do this c(x, u)[order(c(seq_along(x), i))].

+6

-, ( i ):

xn <- rep(NA,length(x))
xn[i] <- u
y <- c(rbind(x,xn))
y <- y[!is.na(y)] 
+1

# vec->source vector, val->values to insert, at->positions to insert

func_insert_vector_at <- function(vec, val, at){
    out=numeric(length(vec)+length(val))
    out[at]=NA
    out[!is.na(out)]=vec
    out[at]=val
    return(out)
}
+1
source

Source: https://habr.com/ru/post/1609771/


All Articles