如何在R中迭代产生组合? [英] How to produce combinations iteratively in R?
问题描述
所以我目前正在使用以下代码生成我的组合:
So I am currently using the following code to generate my combinations:
combn(x,y)
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中迭代产生组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!