17

我正在寻找一种组合两个矩阵的通用方法,以便两个初始矩阵中的列在新矩阵中交替出现

col1m1...col1m2...col2m1...col2m2...col3m1...col3m2...

例如:

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)

我正在寻找一种通用方法,因为我将拥有超过 3 列的矩阵组合。我尝试了一些 for 循环和一些 if 语句,但对我来说并没有真正结合在一起。将矩阵与随机播放和交替组合的搜索也没有证明是富有成果的。有什么想法吗?

4

5 回答 5

14

像这样应该做的事情:

m <- cbind(matrix.odd, matrix.even)                   # combine
m <- m[, c(matrix(1:ncol(m), nrow = 2, byrow = T))]   # then reorder

另一个有趣的选择:

matrix(rbind(matrix.odd, matrix.even), nrow = nrow(matrix.odd))

并玩许多矩阵游戏:

weave = function(...) {
  l = list(...)
  matrix(do.call(rbind, l), nrow = nrow(l[[1]]))
}
于 2013-09-17T23:14:38.023 回答
9
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
于 2013-09-17T23:10:19.513 回答
5
alternate.cols <- function(m1, m2) {
  cbind(m1, m2)[, order(c(seq(ncol(m1)), seq(ncol(m2))))]
}

identical(matrix.combined, alternate.cols(matrix.odd, matrix.even))
# [1] TRUE

m1如果并且m2具有不同数量的列,这也可以做正确的事情(主观) :

alternate.cols(matrix.odd, matrix.even[, -3])
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
# [2,]    1    2    3    4    5
# [3,]    1    2    3    4    5

很容易推广到任意数量的矩阵:

alternate.cols <- function(...) {
  l <- list(...)
  m <- do.call(cbind, l)
  i <- order(sequence(sapply(l, ncol)))
  m[, i]
}
于 2013-09-17T23:20:20.903 回答
2

你可以变成一个 3D 数组,然后转置......

arr <- array( c(m1,m2) , dim = c(dim(m1),2) )
matrix( aperm( arr , c(1,3,2) ) , nrow(m1) )
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    3    4    5    6
[2,]    1    2    3    4    5    6
[3,]    1    2    3    4    5    6

作为一个函数,可以推广到许多矩阵......

bindR <- function(...){
    args <- list(...)
    dims <- c( dim(args[[1]]) , length(args) )
    arr <- array( unlist( args ) , dim = dims )
    matrix( aperm( arr , c(1,3,2) ) , dims[1] )
}


bindR(m1,m2,m1,m2)
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
#[1,]    1    2    1    2    3    4    3    4    5     6     5     6
#[2,]    1    2    1    2    3    4    3    4    5     6     5     6
#[3,]    1    2    1    2    3    4    3    4    5     6     5     6
于 2013-09-17T23:20:34.170 回答
0

可能有更简洁的方法来做到这一点。如果矩阵很大,您可能需要寻找更有效的方法。

# Test data
(X <- matrix(1:16, nrow=4, ncol=4))
(Y <- matrix(-16:-1, nrow=4, ncol=4))

# Set indices for the new matrix
X.idx <- seq(1, ncol(X)*2, by=2)
Y.idx <- seq(2, ncol(Y)*2+1, by=2)

# Column bind the matrices and name columns according to the indices
XY <- cbind(X, Y)
colnames(XY) <- c(X.idx, Y.idx)

# Now order the columns
XY[, order(as.numeric(colnames(XY)))]
于 2013-09-17T23:11:05.227 回答