I'm looking for a general approach to combine two matrices so that the columns from the two initial matrices alternate in the new matrix
col1m1...col1m2...col2m1...col2m2...col3m1...col3m2......
for example:
matrix.odd <- matrix(c(rep(1,3),rep(3,3),rep(5,3)),nrow=3,ncol=3)
matrix.even <- matrix(c(rep(2,3),rep(4,3),rep(6,3)),nrow=3,ncol=3)
# would look like
matrix.combined <- matrix(c(rep(1,3),rep(2,3),rep(3,3),rep(4,3),rep(5,3),rep(6,3)),
nrow=3,ncol=6)
I'm looking for a general approach because I will have matrix combinations with more than just 3 columns. I've tried some for loops and some if statements but it isn't really coming together for me. Searches on combining matrices with shuffle and with alternation have not proven fruitful either. Any thoughts?
Smth like this should do:
m <- cbind(matrix.odd, matrix.even) # combine
m <- m[, c(matrix(1:ncol(m), nrow = 2, byrow = T))] # then reorder
Another option for fun:
matrix(rbind(matrix.odd, matrix.even), nrow = nrow(matrix.odd))
And to play the many matrices game:
weave = function(...) {
l = list(...)
matrix(do.call(rbind, l), nrow = nrow(l[[1]]))
}
rows.combined <- nrow(matrix.odd)
cols.combined <- ncol(matrix.odd) + ncol(matrix.even)
matrix.combined <- matrix(NA, nrow=rows.combined, ncol=cols.combined)
matrix.combined[, seq(1, cols.combined, 2)] <- matrix.odd
matrix.combined[, seq(2, cols.combined, 2)] <- matrix.even
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With