Tuesday 15 September 2015

combinations - R: function that returns all the possible ordering of n elements? -


In R, is there a function that gives all the possible order of n elements? I want an N! By N matrix, such that each row has all the possible orderly elements of n elements. That is, if n = 3, I want to:

  1,2,3 1,3,2, 2,1,3, 2,3,1, 3,1,2, 3,2,1  

I first thought that the expansion would occur. The grid works, and tried:

  n & lt; - 3 wide .grid (representative (list (1: n), n)) Var1 Var2 Var3 1 1 1 1 2 2 1 1 3 3 1 1 4 1 2 1 5 2 2 1 6 3 2 1 7 1 3 1 8 2 3 1 9 3 3 1 10 1 1 2 11 2 1 2 12 3 1 2 13 1 2 2 14 2 2 15 3 2 2 16 1 3 2 17 2 3 2 18 3 3 2 1 9 1 1 3 20 2 1 3 21 3 1 3 22 1 2 3 23 2 2 3 24 3 2 3 25 1 3 3 26 2 3 3 27 3 3 3  

But this gives 3 matrix by 3 ^ 3 That is, each row may have duplicate values. ..

try

  library (gtools) permutations (n , 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  

No comments:

Post a Comment