How to merge 2 vectors alternating indexes?

This will work using rbind :

c(rbind(a, b))

For example:

a = c(1,2,3)
b = c(11,12,13)

c(rbind(a,b))

#[1]  1 11  2 12  3 13 

Explanation

This works because R stores arrays in column-major order.

When you rbind() the two vectors, you get:

rbind_result <- rbind(a, b)
rbind_result
#   [,1] [,2] [,3]
# a    1    2    3
# b   11   12   13

Then c() coerces rbind_result into a column-wise flattened vector:

merged <- c(rbind_result)
merged
# [1] 1 11 2 12 3 13

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)