3

I have the vector y=[-2 -4 -6 ... -1000], and I want to insert a 0 before every element to change the vector into: y=[0 -2 0 -4 0 -6 ... 0 -1000].

How do I do this? Should I try to directly insert elements into vector y or create a separate vector z with just 0's and try to merge the 2?

Also, is there a way to do this without using loops or index vectors?

Jess
  • 275
  • 5
  • 12

1 Answers1

5

You could use rbind as follows:

y <- seq(from=2, to=10, by=2)*-1
y
# [1]  -2  -4  -6  -8 -10
as.vector(rbind(0, y))
# [1]   0  -2   0  -4   0  -6   0  -8   0 -10
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485