生成R中矩阵的所有排列

时间:2015-11-16 23:46:54

标签: r permutation

我有以下给出的矩阵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中做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:1)

如何使用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
相关问题