4

For starters, forgive my math terminology ignorance (I'll edit this question, once errors in my vocabulary are pointed out).

How can I print a complete set of 3 element permutation of a 10 element vector in R?

Let's assume a vector consists of 10 unique letters A to J

x<- LETTERS[seq( from = 1, to = 10 )]

I'd like to list (print) all possible 3 unique element permutations, for example:

ABC, ACB, ABD, ADB ... etc

Thank you for any hints

blazej
  • 1,678
  • 3
  • 19
  • 41
  • 1
    You might want to check out [Generating all distinct permutations of a list in R](https://stackoverflow.com/questions/11095992/generating-all-distinct-permutations-of-a-list-in-r), which might be all you need. – PaSTE Sep 26 '17 at 13:22
  • 3
    Or you have a look on package `gtools` with function `permutations(n = 10, r = 3, v = x, repeats.allowed = FALSE)` – wolf_wue Sep 26 '17 at 13:26
  • Looks like permn(x) will print all permutation for the whole vector. I can't figure out how to limit it to a 3 element option. – blazej Sep 26 '17 at 13:27
  • 1
    Thanks @wolf_wue. That's what I was looking for. If you want, I'll accept it as an answer to my question. – blazej Sep 26 '17 at 13:30

2 Answers2

3

This can be easily done using the gtools package.

prm <- gtools::permutations(n=10, r=3, v=LETTERS[1:10])

Then you can apply paste0 across the rows to get a vector.

apply(prm, 1, function(x)paste0(x, collapse=''))
Collin
  • 326
  • 2
  • 6
0

similar to collin using new pipe you can write as:

LETTERS[1:10] |> permutations(n=10,r=3) |> apply(1,paste, collapse = '')