Home > Net >  Create list with all possible combinations from another list in R
Create list with all possible combinations from another list in R

Time:11-22

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 

CodePudding user response:

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"

CodePudding user response:

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"
  • Related