0

I'm trying to build a list/vector/... from something like this:

elements <- c("a","b","c")

that gives me combinations of every entry of elements with all other entries of elements. These combinations should go from length 1 to length(elements). The result should therefore (if I haven't missed a combination) look like this:

combinationsvector <- c("a","b","c", "ab", "ac", "bc", "abc")

or:

combinationslist <- list("a","b","c", "ab", "ac", "bc", "abc")

I don't want to distinguish between "ab" and "ba", those are the same thing for me. This should result in {2^K}-1 combinations (I don't need the empty entry but it wouldn't hurt either). This is for a model averaging exercise and I'm trying to get all possible variable combinations of my dataset. In reality, elements is larger than 3.

Jakob
  • 1,203
  • 12
  • 25
  • its super close and I wouldn't have asked, had I found the other question. I'll leave it though because of what you point out (until we find the real duplicate which probably exists). Thanks! – Jakob Oct 06 '19 at 12:21

1 Answers1

3

Use combn to generate those combinations. combn allows you to pass an anonymous function which can be used to paste the combinations together.

unlist(lapply(sequence(length(elements)), function(i)
    combn(elements, i, function(x) paste(x, collapse = ""))))
#[1] "a"   "b"   "c"   "ab"  "ac"  "bc"  "abc"
d.b
  • 29,772
  • 5
  • 24
  • 63