Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all distinct permutations of a list in R

Tags:

r

permutation

I'm trying to create a list of permutations of a list, such that, for example, perms(list("a", "b", "c")) returns

list(list("a", "b", "c"), list("a", "c", "b"), list("b", "a", "c"),      list("b", "c", "a"), list("c", "a", "b"), list("c", "b", "a")) 

I'm not sure how to proceed, any help would be greatly appreciated.

like image 547
tresbot Avatar asked Jun 19 '12 07:06

tresbot


2 Answers

A while back I had to do this in base R without loading any packages.

permutations <- function(n){     if(n==1){         return(matrix(1))     } else {         sp <- permutations(n-1)         p <- nrow(sp)         A <- matrix(nrow=n*p,ncol=n)         for(i in 1:n){             A[(i-1)*p+1:p,] <- cbind(i,sp+(sp>=i))         }         return(A)     } } 

Usage:

> matrix(letters[permutations(3)],ncol=3)      [,1] [,2] [,3] [1,] "a"  "b"  "c"  [2,] "a"  "c"  "b"  [3,] "b"  "a"  "c"  [4,] "b"  "c"  "a"  [5,] "c"  "a"  "b"  [6,] "c"  "b"  "a"  
like image 64
Museful Avatar answered Sep 26 '22 06:09

Museful


combinat::permn will do that work:

> library(combinat) > permn(letters[1:3]) [[1]] [1] "a" "b" "c"  [[2]] [1] "a" "c" "b"  [[3]] [1] "c" "a" "b"  [[4]] [1] "c" "b" "a"  [[5]] [1] "b" "c" "a"  [[6]] [1] "b" "a" "c" 

Note that calculation is huge if the element is large.

like image 20
kohske Avatar answered Sep 23 '22 06:09

kohske