How generate all posible combinations of a vector without repetition in R?

Viewed 1021

Maybe is an easy question, how generate the combination of a vector. I have the next vector.

> x<-1:5
> x
[1] 1 2 3 4 5

So what I want is a combination of all of them but the sequence must not contain same number in the combination and ab==ba, abc==bca==cab, that is:

permut<-c(1:5,12,13,14,15,23,24,25,34,...,123,124,125,134,135,...,1234,1235,...)
permut
[1] 1 2 3 4 5 12 13 14 15 23 24 25 34 ... 123 124 125 134 135 ... 1234 1235

I think the function expand.grid() can be useful but I don't know how use it exactly.

1 Answers

Here is a solution with combn (credits to @Joseph Wood for making my answer much simpler):

as.numeric(unlist(sapply(vec, function(y) combn(vec, y, paste, collapse = ""))))

Result:

 [1]     1     2     3     4     5    12    13    14    15    23    24    25    34    35
[15]    45   123   124   125   134   135   145   234   235   245   345  1234  1235  1245
[29]  1345  2345 12345

You can also make it a function:

all_combn = function(vec){
  as.numeric(unlist(sapply(vec, function(y) combn(vec, y, paste, collapse = ""))))
}

Result:

> all_combn(1:5)
 [1]     1     2     3     4     5    12    13    14    15    23    24    25    34    35
[15]    45   123   124   125   134   135   145   234   235   245   345  1234  1235  1245
[29]  1345  2345 12345

> all_combn(1:6)
 [1]      1      2      3      4      5      6     12     13     14     15     16     23
[13]     24     25     26     34     35     36     45     46     56    123    124    125
[25]    126    134    135    136    145    146    156    234    235    236    245    246
[37]    256    345    346    356    456   1234   1235   1236   1245   1246   1256   1345
[49]   1346   1356   1456   2345   2346   2356   2456   3456  12345  12346  12356  12456
[61]  13456  23456 123456
Related