3

How do we generate in R all possible combinations (of variable length, so that the resulting list can be of length 1, 2 or 3 if there are 3 elements) from a vector of variable length:

# say we have a vector of length 3:
vec = letters[1:3]

ret = list('a', 'b', 'c', 'ab', 'ac', 'bc', 'abc', 'a,b', 'a,c', 'a,bc', 'b,c', 'ac,b', 'ab,c', 'a,b,c')

Thank you!

user971102
  • 3,005
  • 4
  • 30
  • 37
  • @MrFlick This is not a duplicate, it is different results I am after... – user971102 Aug 07 '16 at 01:11
  • What's different?Looks exactly the same to me. – Eiko Aug 07 '16 at 07:26
  • 1
    @MrFlick Please note I am not looking for this (which is the question you marked as duplicate): "a" "b" "ab" "c" "ac" "bc" "abc"; but I am looking for all combinations like this: "a" "b" "c" "ab" "a,b" "ac" "a,c" "bc" "abc" "a,bc" "b,c" "ab,c" "ac,b" "a,b,c" – user971102 Aug 08 '16 at 01:08

1 Answers1

1

Here's one way, but it performs poorly for longer vectors. There's probably a much neater way of doing it, but this might suffice in the meantime.

get_combos <- function(x) {
  x2 <- unlist(lapply(seq_along(x), function(m) 
    sapply(combn(x, m, simplify=FALSE), paste0, collapse='')))
  x3 <- expand.grid(rep(list(x2), length(x)))
  x4 <- sapply(apply(x3, 1, unique), function(x) paste0(sort(x), collapse=','))
  unique(grep('.*([^,]).*\\1', x4, val=TRUE, invert=TRUE))
}

get_combos(letters[1:3])

##  [1] "a"     "a,b"   "a,c"   "a,bc"  "a,b,c" "b"     "b,c"   "ac,b" 
##  [9] "c"     "ab,c"  "ab"    "ac"    "bc"    "abc"  
jbaums
  • 27,115
  • 5
  • 79
  • 119
  • Thanks so much jbaums... So at the end it is 14 combinations for 3 letters, 51 for 4, after that it does become slow but it really helps show the math. Thanks so much! – user971102 Aug 08 '16 at 02:16