简体   繁体   English

如何遍历 R 中长度为 n 的列表的长度为 k 的子集?

[英]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 .我得到两个数字nk ,其中0 < k < n How can I loop over all possible combinations of subsets of length k?如何遍历长度为 k 的子集的所有可能组合?

Eg I have x <- 1:10 .例如,我有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))){
   ...
}

You can use combn to get an array of all the subsets, then convert that into a list using asplit .您可以使用combn获取所有子集的数组,然后使用asplit将其转换为列表。 Just iterate along this list.只需遍历此列表即可。

For example, the following code will print out all the length-3 subsets of x:例如,以下代码将打印出 x 的所有长度为 3 的子集:

x <- 1:10
n <- 10
k <- 3

subsets <- asplit(combn(n, k), 2)

for(i in subsets) {
  print(x[i])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM