在 R 中生成矩阵的所有排列

Generate all permutations of a matrix in R

我有一个矩阵 M 由以下给出:

M <- matrix(1:6, nrow=2, byrow=TRUE)

1 2 3
4 5 6

并且我希望为该矩阵生成所有可能的排列作为列表。阅读 Generating all distinct permutations of a list in R 后,我尝试使用

library(combinat)
permn(M)

但这给了我所有的排列作为一行,而不是我原来的 2 x 3 矩阵。

所以我得到的是

[[1]]
[1] 1 4 2 5 3 6

[[2]]
[1] 1 4 2 5 6 3

[[3]]
[1] 1 4 2 6 5 3
 ...
[[720]]
[1] 4 1 2 5 3 6

但我想要的是让第一行和第二行彼此不同,这样列表看起来更像下面这样:

[[1]]
1 2 3
4 5 6

[[2]]
1 3 2
4 5 6

[[3]]
2 3 1
5 4 6
...

直到我得到所有可能的 M 组合。有没有办法在 R 中做到这一点?

谢谢!

怎么样,用expand.grid得到所有可能的组合?

M <- matrix(1:6, nrow=2, byrow=TRUE)

pcM <- permn(ncol(M))
expP <- expand.grid(1:length(pcM), 1:length(pcM))

Map(
  function(a,b) rbind( M[1, pcM[[a]]], M[2, pcM[[a]]] ),
  expP[,1],
  expP[,2]
)

#[[1]]
#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    4    5    6
#
#...
#
#[[36]]
#     [,1] [,2] [,3]
#[1,]    2    1    3
#[2,]    5    4    6