Insert elements into a vector at given indexes

These are all very creative approaches. I think working with indexes is definitely the way to go (Marek’s solution is very nice).

I would just mention that there is a function to do roughly that: append().

probes <- rep(TRUE, 15)
probes <- append(probes, FALSE, after=5)
probes <- append(probes, FALSE, after=11)

Or you could do this recursively with your indexes (you need to grow the “after” value on each iteration):

probes <- rep(TRUE, 15)
ind <- c(5, 10)
for(i in 0:(length(ind)-1)) 
    probes <- append(probes, FALSE, after=(ind[i+1]+i))

Incidentally, this question was also previously asked on R-Help. As Barry says:

“Actually I’d say there were no ways of doing this, since I dont think you can actually insert into a vector – you have to create a new vector that produces the illusion of insertion!”

Leave a Comment