考虑这个功能
library(plyr)
all.subsets <- function(set) {
n <- length(set)
bin <- expand.grid(rlply(n, c(F, T)))
mlply(bin, function(...) { set[c(...)] })
}
(参考:http://www.r-bloggers.com/generating-all-subsets-of-a-set/)
我使用它如下:
members <- c('a','b','c','d')
subsets <- all.subsets(members)
现在,如何排除那些length(subsets[i])
&gt; 3
答案 0 :(得分:1)
最小的改变是在你的all.subsets函数中添加一个额外的参数n_max
并通过rowSums过滤内部:
all.subsets <- function(set, max_n) {
n <- length(set)
bin <- expand.grid(rlply(n, c(F, T)))
bin <- bin[rowSums(bin) <= max_n,]
mlply(bin, function(...) { set[c(...)] })
}
subsets <- all.subsets(members, max_n = 3)