如何从 2 个或更多矩阵的所有可能组合创建矩阵?

How to create a matrix from all possible combinations of 2 or more matrices?

假设有两个矩阵:

A <- B <- diag(3)  
> A
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

我想创建一个新的矩阵AB,它由A行和B行的所有可能组合组成。预期结果:

> AB
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    0    0    1    0    0
 [2,]    1    0    0    0    1    0
 [3,]    1    0    0    0    0    1
 [4,]    0    1    0    1    0    0
 [5,]    0    1    0    0    1    0
 [6,]    0    1    0    0    0    1
 [7,]    0    0    1    1    0    0
 [8,]    0    0    1    0    1    0
 [9,]    0    0    1    0    0    1

如何有效地做到这一点?是否可以扩展为两个以上的矩阵?

您可以使用 expand.grid() 并使用其输出来索引矩阵 A 和 B,

x <- expand.grid(1:3,1:3)

cbind(A[x[,1],], B[x[,2],])

给予,

     [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    0    0    1    0    0
 [2,]    0    1    0    0    1    0
 [3,]    0    0    1    0    0    1
 [4,]    1    0    0    1    0    0
 [5,]    0    1    0    0    1    0
 [6,]    0    0    1    0    0    1
 [7,]    1    0    0    1    0    0
 [8,]    0    1    0    0    1    0
 [9,]    0    0    1    0    0    1

编辑:

对于两个以上的矩阵,可以使用如下函数,

myfun <- function(...) {

     arguments <- list(...)

     a <- expand.grid(lapply(arguments, function(x) 1:nrow(x)))
    
    
     do.call(cbind,lapply(seq(a),function(x) { arguments[[x]][a[,x],] }))

 
}

out <- myfun(A,B,C)

head(out)

给予,

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    0    0    1    0    0    1    0    0     0
[2,]    0    1    0    1    0    0    1    0    0     0
[3,]    0    0    1    1    0    0    1    0    0     0
[4,]    1    0    0    0    1    0    1    0    0     0
[5,]    0    1    0    0    1    0    1    0    0     0
[6,]    0    0    1    0    1    0    1    0    0     0

数据:

A <- B <- diag(3)
C <- diag(4)