1

I have the vector:

x = 1,2,3,4,5,6,7

I would like to make it:

x = 1,2,3,0,0,0,4,5,6,0,0,7

inserting the element 0 into x at the proper positions ind. I happen to know that

ind = 4,5,6,10,11

In the problem, ind is specified as the position of each inserted 0 in the new version of x. This is a toy problem. In reality x and ind are 1000s of elements long, and memory is very tight. I have seen some threads that seem related but they do not solve the problem. Given ind, they would create

 x = 1 2 3 4 0 5 0 6 0 7 0 0

which is wrong (it misinterprets the insertion points).

Community
  • 1
  • 1
stan
  • 35
  • 6

1 Answers1

0

One option would be

v1 <- numeric(length(x)+length(ind))
v1[setdiff(seq_along(v1), ind)]  <- x
v1
#[1] 1 2 3 0 0 0 4 5 6 0 0 7

data

x <- 1:7
ind <- c(4:6,10:11)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks Akrun. It would be great to have an in-place solution, i.e. just using x instead of creating a new variable. The reason is that memory is very tight. x is huge – stan Feb 25 '16 at 07:53