简体   繁体   English

如何避免R中有10个嵌套循环?

[英]How can I avoid having 10 nested loops in R?

I am trying to do the following in R : get every vector of the type 我正在尝试在R中执行以下操作:获取该类型的每个向量

c(a1, a2, ... , a10) , where c(a1, a2, ... , a10) ,其中

a1 < a2 < ... < a10 , and a1 < a2 < ... < a10 ,以及

a1, ... , a10 in c(1:100) . a1, ... , a10 in c(1:100)

This is possible using nested loops, with 使用嵌套循环可以实现

for(a1 in 1:90) {

  for(a2 in (a1+1):91) {

for(a3 in (a2+1):92) {

etc... 等等...

But you'll understand why I'd rather avoid that solution. 但是您会理解为什么我宁愿避免该解决方案。 Furthermore, I'd like to be able to make both the number of a's and their range be parametrable, so as to get, for example, (a1, a2, a3) in 1:10 此外,我希望能够同时使a的数量和其范围成为参数,以便获得例如(a1, a2, a3) in 1:10

Does anyone have any idea as to how I might be able to do that? 有没有人对我如何做到这一点有任何想法? Keeping in mind that I do need to go through every possible combination of (a1:a10) , in order to be able to use the result in a later function. 请记住,我确实需要遍历(a1:a10)所有可能组合,以便能够在以后的函数中使用结果。

Let's reduce the problem to a1 < a2 < a3 taken from 1:5 : 让我们将问题简化为从1:5得出的a1 < a2 < a3

combn(5, 3)
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,]    1    1    1    1    1    1    2    2    2     3
#[2,]    2    2    2    3    3    4    3    3    4     4
#[3,]    3    4    5    4    5    5    4    5    5     5 

How many combinations are that? 那有多少种组合?

choose(5, 3)
#[1] 10

How many combinations are that for the problem as stated? 如上所述的问题有多少种组合?

choose(100, 10)
#[1] 1.731031e+13

That's too many to calculate them all. 太多了,无法全部计算出来。

Like this? 像这样?

sapply(0:10,"+",1:90)
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
# [1,]    1    2    3    4    5    6    7    8    9    10    11
# [2,]    2    3    4    5    6    7    8    9   10    11    12
# [3,]    3    4    5    6    7    8    9   10   11    12    13
# [4,]    4    5    6    7    8    9   10   11   12    13    14

Each column is your vector. 每列都是您的向量。 Column 1 is 1-90, column 2 is 2-91,...,column 11 is 11-100. 第1列是1-90,第2列是2-91,...,第11列是11-100。

You will have a lot of combinations! 您将有很多组合!

Here's a function to make it, but I can't get more than 4 numbers using 1:100 without running for a long time on my computer. 这是一个实现它的功能,但是如果不在计算机上长时间运行,使用1:100最多只能得到4个数字。

getcombinations<-function(size, maxn){
 as.data.frame(t(combn(seq(from=1,to=maxn),size)))
}

It works by using combn to take all the combinations of size from the seq(1:maxn) , then rearranging a little. 它通过使用combnseq(1:maxn)中获取大小的所有组合,然后重新排列一点来工作。

getcombinations(3,4)
  V1 V2 V3
1  1  2  3
2  1  2  4
3  1  3  4
4  2  3  4

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

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