Generating all distinct permutations of a list in R

tresbot picture tresbot · Jun 19, 2012 · Viewed 78.9k times · Source

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.

Answer

kohske picture kohske · Jun 19, 2012

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.