1

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))){
   ...
}
Corram
  • 233
  • 1
  • 3
  • 13

1 Answers1

2

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])
}
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87