16

I have a for loop nested in another for loop. How can I make it so that when something happens in the inner loop, we exit and jump to the next iteration of the outer loop?

u <- 0

for (i in 1:100) {
    u <- u + 1
    j <- 1000
    for (e in 1:30) {
        j <- j - 1
        if (j < 990) {
            # if j is smaller than 990 I hope start next time of i
        }
    }
}
dnerever
  • 5
  • 3
user1421972
  • 161
  • 1
  • 1
  • 5
  • 2
    See: `next` and `break`, but here I would rather have an inner loop like: `for (j in 1000:970) {...}` – daroczig May 28 '12 at 15:22

2 Answers2

17

@flodel has the correct answer for this, which is to use break rather than next. Unfortunately, the example in that answer would give the same result whichever control flow construct was used.

I'm adding the following example just to make clear how the behavior of the two constructs differs.

## Using `break`
for (i in 1:3) {
   for (j in 3:1) {     ## j is iterated in descending order
      if ((i+j) > 4) {
         break          ## << Only line that differs
      } else {
         cat(sprintf("i=%d, j=%d\n", i, j))
      }}}
# i=1, j=3
# i=1, j=2
# i=1, j=1

## Using `next`
for (i in 1:3) {
   for (j in 3:1) {     ## j is iterated in descending order
      if ((i+j) > 4) {
         next           ## << Only line that differs
      } else {
         cat(sprintf("i=%d, j=%d\n", i, j))
      }}}
# i=1, j=3
# i=1, j=2
# i=1, j=1
# i=2, j=2   ##  << Here is where the results differ
# i=2, j=1   ##
# i=3, j=1   ##
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
11

I think you want to use break so R will stop looping through your inner for loop, hence proceed to the next iteration of your outer for loop:

for (i in 1:10) {
   for (j in 1:10) {
      if ((i+j) > 5) {
         # stop looping over j
         break
      } else {
         # do something
         cat(sprintf("i=%d, j=%d\n", i, j))
      }
   }
}
# i=1, j=1
# i=1, j=2
# i=1, j=3
# i=1, j=4
# i=2, j=1
# i=2, j=2
# i=2, j=3
# i=3, j=1
# i=3, j=2
# i=4, j=1
flodel
  • 87,577
  • 21
  • 185
  • 223