问题描述
所以我目前正在使用以下代码来生成我的组合:
So I am currently using the following code to generate my combinations:
combn(x,y)
但问题是函数存储了所有可能的组合.我不想存储它们,我只想像循环或其他东西一样生产它们.这对我的程序来说会更有效率.有没有办法通过 for 循环生成组合而不是全部存储?
But the thing is that function stores all of the possible combinations. I dont want to store them, I just want to produce them through like a loop or something. It would be way more efficient for my program. Is there a way to generate combinations through a for loop rather than storing them all?
我知道我在这里问了一个类似的问题:我如何找到所有可能的在R中迭代的集合的子集?
I know I asked a similar question here:How do I find all possible subsets of a set iteratively in R?
但在那个解决方案中,组合仍然被存储......
But in that solution the combinations are still being stored...
这里有更多细节:
假设我想找到 4 选择 2.combn(4,2) 基本上会存储以下内容:((1,4),(1,3),(1,2),(2,4),(2,3)(3,4))
Lets say I want to find 4 choose 2. combn(4,2) would essentially store the following:((1,4),(1,3),(1,2),(2,4),(2,3)(3,4))
我想要的是这个:
loop{
produces one combination at a time
}
推荐答案
这里有一个建议,它允许根据循环的上一次迭代中使用的组合为循环的当前迭代生成组合.
Here is a suggestion which allows to generate the combination for the current iteration of the loop based on the combination used in the previous iteration of the loop.
## Function definition
gen.next.cbn <- function(cbn, n){
## Generates the combination that follows the one provided as input
cbn.bin <- rep(0, n)
cbn.bin[cbn] <- 1
if (tail(cbn.bin, 1) == 0){
ind <- tail(which(cbn.bin == 1), 1)
cbn.bin[c(ind, ind+1)] <- c(0, 1)
}else{
ind <- 1 + tail(which(diff(cbn.bin) == -1), 1)
nb <- sum(cbn.bin[-c(1:ind)] == 1)
cbn.bin[c(ind-1, (n-nb+1):n)] <- 0
cbn.bin[ind:(ind+nb)] <- 1
}
cbn <- which(cbn.bin == 1)
}
## Example parameters
n <- 6
k <- 3
## Iteration example
for (i in 1:choose(n, k)){
if (i == 1){
cbn <- 1:k
}else{
cbn <- gen.next.cbn(cbn, n)
}
print(cbn)
}
# [1] 1 2 3
# [1] 1 2 4
# [1] 1 2 5
# [1] 1 2 6
# [1] 1 3 4
# [1] 1 3 5
# [1] 1 3 6
# [1] 1 4 5
# [1] 1 4 6
# [1] 1 5 6
# [1] 2 3 4
# [1] 2 3 5
# [1] 2 3 6
# [1] 2 4 5
# [1] 2 4 6
# [1] 2 5 6
# [1] 3 4 5
# [1] 3 4 6
# [1] 3 5 6
# [1] 4 5 6
这篇关于如何在 R 中迭代地产生组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!