Merge & Interleave dataframes in r

You got the first step right, which is cbinding. Let's say your data frames are d1 with n columns A1, A2, ...,An and d1 with n columns B1, B2, ..., Bn. Then d <- cbind(d1, d2) will give you the data frame containing all the information you wanted, and you just need to re-order its columns. This amounts to generating a vector (1, (n+1), 2, (n+2), ..., n, 2n) to index the data frame columns. You can do this as s <- rep(1:n, each = 2) + (0:1) * n. So finally, your desired data frame is d[s].


Similar to @akrun's answer but with indexes instead of names

#example data
set.seed(1)
d1 <- setNames(as.data.frame(matrix(sample(1:10,20, replace=T),5,5)), paste0("A",1:5))
d2 <- setNames(as.data.frame(matrix(sample(1:10,20, replace=T),5,5)), paste0("B",1:5))

#create indexes for the desired order
x <- order(c(1:ncol(d1), 1:ncol(d2)))
x
#[1]  1  6  2  7  3  8  4  9  5 10

#cbind d1 and d2, interleaving columns with x
d <- cbind(d1, d2)[,x]

Tags:

R