Search code examples
rpermutationcombn

How to create all the combinations in a vector using R


I have a vector of n observations. Now I need to create all the possible combinations with those n elements. For example, my vector is

a<-1:4

In my output, combinations should be like,

1

2

3

4

12

13

14

23

24

34

123

124

134

234

1234

How can I get this output?

Thanks in advance.


Solution

  • Something like this could work:

    unlist(sapply(1:4, function(x) apply(combn(1:4, x), 2, paste, collapse = '')))
    

    First we get the combinations using combn and then we paste the outputs together. Finally, unlist gives us a vector with the output we need.

    Output:

    [1] "1"    "2"    "3"    "4"    "12"   "13"   "14"   "23"   "24"   "34"   "123"  "124" 
        "134"  "234"  "1234"