且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在R中迭代地找到集合中所有可能的子集?

更新时间:2023-02-10 07:47:03

无需循环( 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)