Search code examples
rpermutationpermute

Why does the allPerms function in R always give one combination less?


I am trying to find all possible combinations for a number ie essentially the factorial of the number but also have display all possible combinations.

When I use the allPerms function I am supposed to get all possible combinations but it gives always one combination less. Why is this so?

library(permute)
allPerms(3)
     [,1] [,2] [,3]
[1,]    1    3    2
[2,]    2    1    3
[3,]    2    3    1
[4,]    3    1    2
[5,]    3    2    1

allPerms(4)
      [,1] [,2] [,3] [,4]
 [1,]    1    2    4    3
 [2,]    1    3    2    4
 [3,]    1    3    4    2
 [4,]    1    4    2    3
 [5,]    1    4    3    2
 [6,]    2    1    3    4
 [7,]    2    1    4    3
 [8,]    2    3    1    4
 [9,]    2    3    4    1
[10,]    2    4    1    3
[11,]    2    4    3    1
[12,]    3    1    2    4
[13,]    3    1    4    2
[14,]    3    2    1    4
[15,]    3    2    4    1
[16,]    3    4    1    2
[17,]    3    4    2    1
[18,]    4    1    2    3
[19,]    4    1    3    2
[20,]    4    2    1    3
[21,]    4    2    3    1
[22,]    4    3    1    2
[23,]    4    3    2    1

As you can see the very first combinations of 123 and 1234 for both the cases is missing respectively.

I know I can get all possible combinations using the permn() function from combinat package.

I just wanted to know if there is a way to use allPerms itself for this purpose. Or any other function too. Any info on this will be very useful. Thank you.


Solution

  • You want to set the observed flag to TRUE using the how() helper function.

    h <- how(observed = TRUE)
    allPerms(3, h)
    
    > h <- how(observed = TRUE)
    > allPerms(3, h)
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    1    3    2
    [3,]    2    1    3
    [4,]    2    3    1
    [5,]    3    1    2
    [6,]    3    2    1
    

    Why is observed = FALSE the default? Well, this is intentional because the entire package was designed from the viewpoint of restricted permutation tests that are common in applied uses of ordination methods in ecology. Given that we already have the observed permutation, the data, we don't want it in the permutations used to define the null distribution of the test statistic; well we do, but only through the observed data, not any extra ones that might come up during permutation.