Dirk W
Dirk W

Reputation: 31

Nested for loops in R, termination

Here is some unexpected R behavior.

for(i in 1:3)
{
  for(j in (i+1):3)
  {
    print(paste(i,j))
  }
}

yields:

[1] "1 2"
[1] "1 3"
[1] "2 3"
[1] "3 4"
[1] "3 3"

Why does it not stop at "2 3"?

Upvotes: 1

Views: 79

Answers (1)

loki
loki

Reputation: 10350

That is because in the second for for loop you go from 4 to 3 backwards when i = 3. R includes both the lower and the upper number in the sequence (in contrast to many other languages). Thus, 1:3 will return a vector of c(1,2,3) including both 1 and 3.

Check ?`:` for more information.

Therefore, the loop continues to run. To stop the running loop, you might consider ?break inside an if check, or reconsider the ranges your loops will be applied to.

Upvotes: 3

Related Questions