In a previous post, I used itertools in Python to create combination and permutation using the standard module itertools. What about using R language to perform the same task.
The permutation function allows you to get permutation of N values within a list, where order matters. For instance, selecting N=2 values with [1,2,3] is done as follows:
>>> print list(itertools.permutations([1,2,3], 2)) [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] |
using R, you can use the combinations package (could not find anything in the standard R library but I’m sure it exists…)
If order is not important, you can use combinations:
>>> print list(itertools.combination([1,2,3], 2)) [(1, 2), (1, 3), (2, 3)] |
using R, you can use:
> combn(seq(1:3), 2) [,1] [,2] [,3] [1,] 1 1 2 [2,] 2 3 3 |
Then, you may want to build all possible arrays of N values taken from a list of possible values. For instance, you may want to build a vector of length N=3 made of 0 and 1. This can be done with the cartesian product function:
>>> print list(itertools.product([0,1], repeat=3)) [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] |
In R, you can use the expand function
>>>expand.grid(rep(list(0:1), 3)) Var1 Var2 Var3 1 0 0 0 2 1 0 0 3 0 1 0 4 1 1 0 5 0 0 1 6 1 0 1 7 0 1 1 8 1 1 1 |
In other word, expand.grid can be used to build a permutation with repetitions.