5

I have a matrix M given by the following:

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

1 2 3
4 5 6

and I wish to generate all possible permutations for this matrix as a list. After reading Generating all distinct permutations of a list in R, I've tried using

library(combinat)
permn(M)

but this gives the me all the permutations as a single row, and not the 2 x 3 matrix I had originally.

So what I get is something like

[[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

But what I want is to keep the first and second rows distinct from each other so it would be a list that looks more like the following:

[[1]]
1 2 3
4 5 6

[[2]]
1 3 2
4 5 6

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

until I get all possible combinations of M. Is there a way to do this in R?

Thank you!

Community
  • 1
  • 1
Nel Lau
  • 149
  • 2
  • 8
  • 2
    `lapply(permn(ncol(M)), function(x) M[, x])` or similar. – Frank Nov 16 '15 at 23:56
  • 1
    Is that right Frank.? Should it not be every permutation in first row be with every permutation from second? (ie look at first two entries of solution) – user20650 Nov 16 '15 at 23:59
  • Oh I see, you're permuting the rows independently? That's a lot of combos for a moderately-large matrix... hm, not sure how to do that. – Frank Nov 17 '15 at 00:07
  • `lapply(permn(M),matrix,nrow=2)` ? – Ben Bolker Nov 17 '15 at 00:20
  • @Frank - yes, I'm trying to permute each row independently to get every possible permutation of M. – Nel Lau Nov 17 '15 at 01:25
  • If you want to permute each row independently, that means the number 1 never appears in the 2nd row, and the number 4 never appears in the 1st row. This means you will not get all possible permutations of M because swapping 1 and 4 is one possible permutation. – perfectlyGoodInk May 19 '19 at 13:06

1 Answers1

1

How about this, using expand.grid to get all the possibilities of combinations?

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
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • How about extending to more rows? – Frank Nov 17 '15 at 00:24
  • 1
    @Frank - I'll leave that for OP - `expP <- do.call(expand.grid, rep(list(1:length(pcM)), nrow(M)) )` would cover the first part. – thelatemail Nov 17 '15 at 00:31
  • @thelatemail - when I tried your implementation, I found that it seemed permute each column, but I'm trying to permute the numbers within each row independently to get every possible combination of M. – Nel Lau Nov 17 '15 at 01:24
  • 1
    @NelLau This works for me, maybe try running just the code in this answer and see if it matches what you expect. – Frank Nov 17 '15 at 01:29