给定一个向量,返回最大为n的所有组合的列表 [英] Given a vector, return a list of all combinations up to size n

查看:50
本文介绍了给定一个向量,返回最大为n的所有组合的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中编写一个函数,给定一个向量和最大大小n,它将返回该向量中所有元素的组合,直到大小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.

例如:

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"

我想出了一种巧妙的方法来运行 combn ,每个大小最多为n,但是我可以似乎没有将结果合并到一个列表中。有建议吗?

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?

推荐答案

尝试一下:

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

返回

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

这篇关于给定一个向量,返回最大为n的所有组合的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆