Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...