如何在R中迭代地找到集合中所有可能的子集? [英] How do I find all possible subsets of a set iteratively in R?
问题描述
所以我知道以下命令会在列表中存储所需长度y的所有可能组合,其中 y< j
:
So I know that the following command would store all possible combinations of a desired length y in a list, where y < j
:
lapply(y, function(x) combn(j,x))
但我不希望它们全部存储在列表中,因为稍后我只会访问它们曾经如此,将它们存储在内存中效率不高。有没有办法我可以在某种循环或其他东西中生成每个组合,然后在我完成计算后,它会给我下一个组合?所以基本上我想迭代地生成组合而不是先存储它们。
But I don't want them all to be stored in a list because later on I will be accessing them only once so it's not efficient to store them in memory. Is there a way where I can just produce each combination in some sort of a loop or something, and then after I'm done performing a calculation, it would just give me the next combination? So basically I want to produce the combinations iteratively instead of storing them first.
所以在伪代码中,我想要的是:
So in pseudo code, what i'd like to have is:
#loop that will generate each possible combination one by one
loop{
operation that uses combination
}
推荐答案
无需循环( lapply
或其他):
combn(1:4,2)
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1 1 1 2 2 3
# [2,] 2 3 4 3 4 4
计算组合总和的示例:
combn(1:4,2,FUN=sum)
# [1] 3 4 5 5 6 7
用户定义函数的示例:
x <- 11:14
combn(1:4,2,FUN=function(i,a) sum(a[i]),a=x)
#[1] 23 24 25 25 26 27
这里(在匿名的乐趣中) ction) i
是用作索引和参数的组合 a
是我传递的向量 x
。
Here (in the anonymous function) i
is the combination used as index and argument a
is a vector to which I pass x
.
与用户定义的命名函数相同:
And the same with a user-defined named function:
fun <- function(i,a) sum(a[i])
combn(1:4,2,FUN=fun,a=x)
这篇关于如何在R中迭代地找到集合中所有可能的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!