Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

Weird R nested for loop behavior

I have the following code:

for(i in(1:5) )
{
    for(j in ( (i+1) :5) )
{
    cat (i,", ",j,"\n")

}
}

My expectation is, it will list all pair of numbers from 1 to 5. However, I am getting the following when I run the above R script.

1 ,  2 
1 ,  3 
1 ,  4 
1 ,  5 
2 ,  3 
2 ,  4 
2 ,  5 
3 ,  4 
3 ,  5 
4 ,  5 
5 ,  6 
5 ,  5 

The last two rows are totally puzzling me. Had this been a case of border inclusion/exclusion, 6 would always be printed after 1,2,3,4, but it's only happening after 5. Also, the last pair of 5,5 makes no sense either.

Upvotes: 0

Views: 156

Answers (4)

Jilber Urbina
Jilber Urbina

Reputation: 61164

I thihk your loop should be,

for(i in(1:5) )
{
  for(j in ( (i) :5) )
  {
    cat (i,", ",j,"\n")

  }
}

1 ,  1 
1 ,  2 
1 ,  3 
1 ,  4 
1 ,  5 
2 ,  2 
2 ,  3 
2 ,  4 
2 ,  5 
3 ,  3 
3 ,  4 
3 ,  5 
4 ,  4 
4 ,  5 
5 ,  5 

Update

In order to get results similar to those of combn just an if(·) condition as in:

for(i in(1:5) )
{
  for(j in ( (i) :5) )
  {
    if(i!=j){
      cat (i,", ",j,"\n")
    }

  }
}

This way you avoid printing values when i is equal to j (I think this is what you called "repeated value pair").

Upvotes: 3

Ferdinand.kraft
Ferdinand.kraft

Reputation: 12819

You can get that using this:

t(combn(5, 2))

Result:

      [,1] [,2]
 [1,]    1    2
 [2,]    1    3
 [3,]    1    4
 [4,]    1    5
 [5,]    2    3
 [6,]    2    4
 [7,]    2    5
 [8,]    3    4
 [9,]    3    5
[10,]    4    5

Upvotes: 2

Andrew_someNumber
Andrew_someNumber

Reputation: 13

Try to write if state. Something like

for(i in(1:5) )
{
    if (i < 4) {
        for(j in ( (i+1) :5) )
        {
            cat (i,", ",j,"\n")
        }
    }
}

Upvotes: 0

eddi
eddi

Reputation: 49448

It does exactly what you asked it to do:

6:5
#[1] 6 5

See

?`:`

for more info.

Upvotes: 4

Related Questions