user971102 - 1 year ago 82

R Question

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!

Answer Source

Here's a fairly kludgy way of doing it, which treats the result as a string with five characters (`'a'`

, `','`

, `'b'`

, `','`

, `'c'`

) that can be switched on or off.

```
get_combos <- function(x) {
x1 <- expand.grid(rep(list(0:1), length(x)*2-1))
x2 <- mapply(function(x, char) {
ifelse(x==1, char, '')
}, x1, strsplit(paste0(x, collapse=','), '')[[1]])
x3 <- apply(x2, 1, paste, collapse='')
grep('^$|,,|^,|,$', x3, value=TRUE, invert=TRUE)
}
get_combos(letters[1:3])
## [1] "a" "b" "ab" "a,b" "c" "ac" "a,c" "bc" "abc" "a,bc"
## [11] "a,c" "b,c" "ab,c" "a,b,c"
```

Another example:

```
get_combos(LETTERS[1:4])
## [1] "A" "B" "AB" "A,B" "C" "AC" "A,C" "BC"
## [9] "ABC" "A,BC" "A,C" "B,C" "AB,C" "A,B,C" "D" "AD"
## [17] "A,D" "BD" "ABD" "A,BD" "A,D" "B,D" "AB,D" "A,B,D"
## [25] "CD" "ACD" "A,CD" "BCD" "ABCD" "A,BCD" "A,CD" "B,CD"
## [33] "AB,CD" "A,B,CD" "A,D" "B,D" "AB,D" "A,B,D" "C,D" "AC,D"
## [41] "A,C,D" "BC,D" "ABC,D" "A,BC,D" "A,C,D" "B,C,D" "AB,C,D" "A,B,C,D"
```