如何在 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
或其他):
No need for loops (lapply
or otherwise):
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
一个用户定义函数的例子:
An example with a user defined function:
x <- 11:14
combn(1:4,2,FUN=function(i,a) sum(a[i]),a=x)
#[1] 23 24 25 25 26 27
这里(在匿名函数中)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屋!