Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: generate all permutations of vector without duplicated elements

Tags:

r

Is there a straightforward way to generate all possible permutations of a vector of integers (1 to max 999) that specifically excludes duplicated elements?

For example, for a vector with three elements in a range of 1 to 9 the sequence 1 2 3 would be acceptable, as would 1 2 9 but 1 2 2 would be invalid. The sequence must contain exactly n elements (in this case, three). EDIT: to avoid confusion, the order is significant, so 1 2 9 and 9 2 1 are both valid and required.

There are many questions on permutations and combinations using R on SO (such as this and this) but none that seem to fit this particular case. I'm hoping there's an obscure base R or package function out there that will take care of it without me having to write a graceless function myself.

like image 395
SlowLearner Avatar asked Feb 05 '13 09:02

SlowLearner


3 Answers

Using gtools package:

require(gtools)
permutations(n = 9, r = 3, v = 1:9)
# n -> size of source vector
# r -> size of target vector
# v -> source vector, defaults to 1:n
# repeats.allowed = FALSE (default)
like image 97
Arun Avatar answered Oct 15 '22 04:10

Arun


utils::combn ; combinat::combn or combinat::permn are alternatives.

like image 11
Carl Witthoft Avatar answered Oct 15 '22 02:10

Carl Witthoft


EDIT: This is not what the OP asked for, but I leave this answer, to avoid confusion.

My math is a little bit rusty, but i think you are describing combinations, not permutations. The base functioncombn() returns combinations.

I illustrate with a manageable set - all combinations of length 3, from the vector 1:4:

combn(4, 3)
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    2
[2,]    2    2    3    3
[3,]    3    4    4    4

The difference between combinations and permutations is that in combinations the order doesn't matter. So, (2, 3, 4) and (4, 3, 2) is the same combination, but different permutations.

like image 10
Andrie Avatar answered Oct 15 '22 02:10

Andrie