Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate all permutations of a matrix in R

Tags:

r

permutation

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!

like image 345
Nel Lau Avatar asked Nov 09 '22 01:11

Nel Lau


1 Answers

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
like image 172
thelatemail Avatar answered Nov 15 '22 07:11

thelatemail