rfor-loopsubset-sum

How to loop over subsets of length k of a list of length n in R?


I am given two numbers n and k with 0 < k < n. How can I loop over all possible combinations of subsets of length k?

E.g. I have x <- 1:10. Then I want to do

for (y in c(c(1,2,3), c(1,2,4), c(1,2,5), ..., c(8, 9, 10))){
   ...
}

Solution

  • You can use combn to get an array of all the subsets, then convert that into a list using asplit. Just iterate along this list.

    For example, the following code will print out all the length-3 subsets of x:

    x <- 1:10
    n <- 10
    k <- 3
    
    subsets <- asplit(combn(n, k), 2)
    
    for(i in subsets) {
      print(x[i])
    }