use*_*984 -5 iteration combinations loops r
所以我知道以下命令会在列表中存储所需长度y的所有可能组合,其中y < j:
lapply(y, function(x) combn(j,x))
Run Code Online (Sandbox Code Playgroud)
但是我不希望它们全部存储在列表中,因为稍后我将只访问它们一次,因此将它们存储在内存中效率不高.有没有办法让我可以在某种循环或其他东西中生成每个组合,然后在我完成计算后,它会给我下一个组合?所以基本上我想迭代地生成组合而不是先存储它们.
所以在伪代码中,我想拥有的是:
#loop that will generate each possible combination one by one
loop{
operation that uses combination
}
Run Code Online (Sandbox Code Playgroud)
Rol*_*and 12
不需要循环(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
Run Code Online (Sandbox Code Playgroud)
计算组合总和的示例:
combn(1:4,2,FUN=sum)
# [1] 3 4 5 5 6 7
Run Code Online (Sandbox Code Playgroud)
具有用户定义函数的示例:
x <- 11:14
combn(1:4,2,FUN=function(i,a) sum(a[i]),a=x)
#[1] 23 24 25 25 26 27
Run Code Online (Sandbox Code Playgroud)
这里(在匿名函数中)i是用作索引的组合,参数a是我传递的向量x.
与用户定义的命名函数相同:
fun <- function(i,a) sum(a[i])
combn(1:4,2,FUN=fun,a=x)
Run Code Online (Sandbox Code Playgroud)