gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:32:05 24 4
gpt4 key购买 nike

假设有两个矩阵:

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)

关于r - 如何从 2 个或更多矩阵的所有可能组合创建矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68356711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com