简体   繁体   中英

Create list with all possible combinations from another list in R

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 

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"

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM