2

I am new to R language. I came to a situation where I need to fill the zero at alternate Position in the vector. for Example:

v<-c(1,2,3,4,5,6,7,8,9,10)

I need the new vector like

0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10

I tried with for loop to fill the zero but I am not able to do.

Saurabh
  • 867
  • 3
  • 13
  • 28

3 Answers3

8

I am sure there are plenty of solutions, but

as.vector(rbind(0,v))
 [1]  0  1  0  2  0  3  0  4  0  5  0  6  0  7  0  8  0  9  0 10

will do it.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • @thelatemail.. Thanks a lot its working fine. I like this approach very much it is very precise way though Tyler's answer is also precise both answer are good and useful for me :) – Saurabh Feb 11 '13 at 07:23
6

A couple of approaches

Create a vector of zeros and then replace the correct indices

x1 <- rep(0, length(x)*2)
x1[seq(2,20,by=2)] <- x

or use Map and c

 unlist(Map(c,0,x))
mnel
  • 113,303
  • 27
  • 265
  • 254
3

Just for kicks:

v <- c(1,2,3,4,5,6,7,8,9,10)
c(mapply(c, 0, v))
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519