Search code examples
rvectorsequences

R: how to get elements from a vector into specific positions of a new vector


I'm using R and I have the following vectors:

odd<- c(1,3,5,7,9,11,13,15,17,19)
even<- c(2,4,6,8,10,12,14,16,18,20)

I want to combine even and odd so I can have a vector (let's say it will be named total) with the following elements

> total
1,2,3,4,5,6,7,8,9,10...,20.

I've tried looping as:

total<- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) #20 elements

for (i in seq(from=1, to=20, by=2)) 
  for (j in seq(from=1, to=10, by=1))
     total[i]<- odd[j]


for (i in seq(from=2, to=20, by=2)) 
      for (j in seq(from=1, to=10, by=1))
         total[i]<- even[j]

But for some reason this is not working. I'm getting this vector

>total
17 20 17 20 17 20 17 20 17 20 17 20 17 20 17 20 17 20 19 20

does anyone no why my looping is not working for this case?

of course, this is only a very simple example of what I have to do with a very large dataset.

thanks!


Solution

  • I believe you problem is because you are adding items from odd(and even in the second loops) to the same position in the total using your code line:

    total[i]<- odd[j]
    

    try this instead;

    odd<- c(1,3,5,7,9,11,13,15,17,19)
    even<- c(2,4,6,8,10,12,14,16,18,20)
    
    elements = 20
    total<- rep(x=0, times=elements) #20 elements
    
    total[seq(from=1, to=length(total), by=2)] = odd
    total[seq(from=2, to=length(total), by=2)] = even
    total
    
    [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
    

    seq creates a sequence of values that I have used here to identify positions to insert the values from odd and even.