Given a vector, return a list of all combinations up to size n

两盒软妹~` 提交于 2019-12-20 02:45:07

问题


I'm trying to write a function in R that, given a vector and a maximum size n, will return all the combinations of elements from that vector, up to size n.

E.g.:

multi_combn(LETTERS[1:3], 2)

Would yield:

[[1]]
[1] "A"

[[2]]
[1] "B"

[[3]]
[1] "C"

[[4]]
[1] "A" "B"

[[5]]
[1] "A" "C"

[[6]]
[1] "B" "C"

I've figured out an inelegant way to run combn for each size up to n, but I can't seem to combine the results into a single list. Any suggestions?


回答1:


Try this:

multi_combn <- function(dat, n) {
    unlist(lapply(1:n, function(x) combn(dat, x, simplify=F)), recursive=F)
}

which returns

> multi_combn(LETTERS[1:3], 2)
[[1]]
[1] "A"

[[2]]
[1] "B"

[[3]]
[1] "C"

[[4]]
[1] "A" "B"

[[5]]
[1] "A" "C"

[[6]]
[1] "B" "C"



回答2:


Just for fun, here are a couple of completely different approaches:

Alternative 1:

multi_combn <- function(X) {
    ii <- do.call(expand.grid, 
                  replicate(length(X), c(FALSE, TRUE), simplify=FALSE))[-1,]
    apply(ii, 1, function(i) X[i])
}
multi_combn(LETTERS[1:3])

Alternative 2: (I don't usually like obfuscated code, but this function's an exception.)

multi_combn <- function(X) {
    sapply(seq_len(2^(length(X)) - 1), 
           FUN = function(n) {
               X[as.logical(rawToBits(as.raw(n)))]
           })
}    
multi_combn(LETTERS[1:3])



回答3:


Not exactly the same format as your desired output, but maybe close enough?

multi_combn <- function(dat, n) {
    lapply(seq_len(n), function(x) t(combn(dat, x))) 
}

> dat <- LETTERS[1:3]
> multi_combn(dat,3)
[[1]]
     [,1]
[1,] "A" 
[2,] "B" 
[3,] "C" 

[[2]]
     [,1] [,2]
[1,] "A"  "B" 
[2,] "A"  "C" 
[3,] "B"  "C" 

[[3]]
     [,1] [,2] [,3]
[1,] "A"  "B"  "C" 


来源:https://stackoverflow.com/questions/13258586/given-a-vector-return-a-list-of-all-combinations-up-to-size-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!