简体   繁体   中英

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

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

a1 < a2 < ... < a10 , and

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

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.

Let's reduce the problem to a1 < a2 < a3 taken from 1:5 :

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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