【发布时间】:2014-06-10 02:44:09
【问题描述】:
我有这个 R 函数来生成一个矩阵,该矩阵由 0 到 n 之间的 k 个数字的所有组合组成,其总和等于 n。这是我的程序的瓶颈之一,因为即使数量很少,它也会变得非常慢(因为它正在计算幂集)
这里是代码
sum.comb <-
function(n,k) {
ls1 <- list() # generate empty list
for(i in 1:k) { # how could this be done with apply?
ls1[[i]] <- 0:n # fill with 0:n
}
allc <- as.matrix(expand.grid(ls1)) # generate all combinations, already using the built in function
colnames(allc) <- NULL
index <- (rowSums(allc) == n) # make index with only the ones that sum to n
allc[index, ,drop=F] # matrix with only the ones that sum to n
}
【问题讨论】:
-
您应该删除部分数据集。例如在查看 n-z 时,您只想考虑 k = 2 时的数字 1:z。如果 k = 3,则使用相同的算法从第三列中删除数字,等等。
-
@HansRoggeman 所以这意味着几个嵌套的 for 循环还是有更优雅的方式?
-
n 和 k 的典型值是多少?不同的算法可能在飞机的不同部分表现更好。至少我们可以尝试改善您的情况。
-
Tite 应该反映“如何在 R 中有效地生成整数分区/组合?”
标签: r performance optimization