问题描述
我在 R 中有一个 data.table,例如:
x <- data.table( id = c(1:10),count=c(10,110,20,30,5,40,50,15,70))
我想分别选择 id 的所有子集,其中 count 的 rowsum 介于 90 和 110 之间。 一种组合是 105
id IN (1,3,4,6)
因为计数的总和是
x[id %in% c(1,6),sum(count)]
如何获得所有可能的组合?
解决方法
这是您当前数据集的强力解决方案
p <- crossprod(
x$count,sapply(
seq(2^nrow(x)),function(n) head(as.integer(intToBits(n)),nrow(x))
)
)
res <- lapply(
which(p >= 90 & p <= 110,arr.ind = TRUE)[,"col"],function(i) x$id[which(head(intToBits(i),nrow(x)) > 0,arr.ind = TRUE)]
)
你会看到
> head(res)
[[1]]
[1] 2
[[2]]
[1] 3 4 6
[[3]]
[1] 1 3 4 6
[[4]]
[1] 3 4 5 6
[[5]]
[1] 1 3 4 5 6
[[6]]
[1] 1 4 7
但是,对于具有更多 id 的大型数据集,它不会扩展。