How do I find all possible subsets of a set iteratively in R?

后端 未结 1 789
迷失自我
迷失自我 2020-12-18 17:52

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(         


        
1条回答
  •  有刺的猬
    2020-12-18 18:02

    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
    

    Example with calculating the sums of combinations:

    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
    

    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)
    

    0 讨论(0)
提交回复
热议问题