2

Create list with all possible combinations from another list in R

Ive seen people ask this question but only found threads with answers for other software and not I R

Basically I just want to create a list with all unique combinations possible

Desired input

a, b, c 

desired output

a, ab, ac, b, bc, c, abc 
Sotos
  • 51,121
  • 6
  • 32
  • 66
  • 1
    Does this answer your question? [Unordered combinations of all lengths](https://stackoverflow.com/questions/27953588/unordered-combinations-of-all-lengths) – Joseph Wood Nov 22 '22 at 16:32

2 Answers2

3

One possibility

> x=letters[1:3] 
> rapply(sapply(seq_along(x),function(y){combn(x,y,simplify=F)}),paste0,collapse="")
[1] "a"   "b"   "c"   "ab"  "ac"  "bc"  "abc"
user2974951
  • 9,535
  • 1
  • 17
  • 24
3

You can try combn to produce all those combinations

> x <- head(letters, 3)

> unlist(lapply(seq_along(x), combn, x = x, simplify = FALSE), recursive = FALSE)
[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

[[4]]
[1] "a" "b"

[[5]]
[1] "a" "c"

[[6]]
[1] "b" "c"

[[7]]
[1] "a" "b" "c"

or

> unlist(lapply(seq_along(x), function(k) combn(x, k, paste0, collapse = "")))
[1] "a"   "b"   "c"   "ab"  "ac"  "bc"  "abc"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81