Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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))){
   ...
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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])
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading