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)
.
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
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
Another option that works also well when the length
of the vector
s are not the same would be to order
by the concatenated sequence of both vector
s
c(a,b)[order(c(seq_along(a), seq_along(b)))]
#[1] 1 5 2 6 3 7 4 8
a <- c(1, 2, 3, 4)
b <- c(5, 6, 7, 8)