1

How to crossly merge two vectors in R?

For example, from c(1,2,3,4) and c(5,6,7,8) to construct c(1,5,2,6,3,7,4,8).

lmo
  • 37,904
  • 9
  • 56
  • 69
WCMC
  • 1,602
  • 3
  • 20
  • 32

3 Answers3

4
a <- c(1, 2, 3, 4)
b <- c(5, 6, 7, 8)

ab <- as.vector(matrix(c(a, b), nrow = 2, byrow = TRUE))
ab
[1] 1 5 2 6 3 7 4 8
www
  • 38,575
  • 12
  • 48
  • 84
3

Similar to ycw's method, you could use rbind to construct the matrix and then form a vector with c:

c(rbind(a, b))
[1] 1 5 2 6 3 7 4 8

data

a <- 1:4
b <- 5:8
lmo
  • 37,904
  • 9
  • 56
  • 69
2

Another option that works also well when the length of the vectors are not the same would be to order by the concatenated sequence of both vectors

c(a,b)[order(c(seq_along(a), seq_along(b)))]
#[1] 1 5 2 6 3 7 4 8

data

a <- c(1, 2, 3, 4)
b <- c(5, 6, 7, 8)
akrun
  • 874,273
  • 37
  • 540
  • 662