-1

The function

permutations(n)

from package e1071, returns a matrix containing all permutations of the integers 1:n (one permutation per row). For example:

> permutations(3)
      [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    1    3
[3,]    2    3    1
[4,]    1    3    2
[5,]    3    1    2
[6,]    3    2    1

A weaker meaning of the term permutation indicates those ordered arrangements in which no element occurs more than once, but without the requirement of using all the elements from a given set. I'm considering, in particular, the arrangements of a fixed length k of elements taken from a given set of size n, in other words: k-permutations of n.

How can I obtain a matrix containing all k-permutations of the integers 1:n (one permutation per row)?

Mark
  • 1,577
  • 16
  • 43

2 Answers2

3

The function permutations from gtools is more elaborate than the one from e1071 as it has other arguments as well like r, v etc.

For your case you can use

library(gtools)
gtools::permutations(n,k)

Edit: this function permutations is from gtools package as pointed out by @jaySf

Adding an example of gtools::permutations(3,2)

permutations(3,2)

         [,1] [,2]
    [1,]    1    2
    [2,]    1    3
    [3,]    2    1
    [4,]    2    3
    [5,]    3    1
    [6,]    3    2
SatZ
  • 430
  • 5
  • 14
2

I recommend the arrangements package. After some benchmarks, we concluded that it is very good.

> library(arrangements)
> permutations(3,2)
     [,1] [,2]
[1,]    1    2
[2,]    1    3
[3,]    2    1
[4,]    2    3
[5,]    3    1
[6,]    3    2
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225