Breaking out of nested loops in R

大城市里の小女人 提交于 2019-12-23 10:15:40

问题


Very simple example code (only for demonstration, no use at all):

repeat {
  while (1 > 0) {
    for (i in seq(1, 100)) {
      break # usually tied to a condition
    }
    break
  }
  break
}
print("finished")

I want to break out from multiple loops without using break in each loop separately. According to a similar question regarding python, wrapping my loops into a function seems to be a possible solution, i.e. using return() to break out of every loop in the function:

nestedLoop <- function() {
  repeat {
    while (1 > 0) {
      for (i in seq(1, 100)) {
        return()
      }
    }
  }
}

nestedLoop()
print("finished")

Are there other methods available in R? Maybe something like labeling loops and then specifying which loop to break (like in Java) ?


回答1:


Using explicit flags, and breaking out of loops conditionally on those flags can give one more flexibility. Example:

stop = FALSE
for (i in c(1,2,3,4)){
    for (j in c(7,8,9)){
        print(i)
        print(j)
        if (i==3){
            stop = TRUE # Fire the flag, and break the inner loop
            break
        }
        }
    if (stop){break} # Break the outer loop when the flag is fired
    }

The above code will break the two nested loops when i=3. When the last line (if (stop){break}) is commented out, then only the inner loop gets broken at i=3, but the outer loop keeps running, i.e. it practically skips the cases of i=3. This structure is easy to play around with, and is as flexible as one may need.




回答2:


I think your method of wrapping your nested loops into a function is the cleanest and probably best approach. You can actually call return() in the global environment, but it will throw an error and looks ugly, like so:

for (i in 1:10) {
  for (a in 1:10) {
    for(b in 1:10) {

      if (i == 5 & a == 7 & b == 2) { return() }

    }
  }
}

print(i)
print(a)
print(b)

Which looks like this in the command line:

> for (i in 1:10) {
+   for (a in 1:10) {
+     for(b in 1:10) {
+       
+       if (i == 5 & a == 7 & b == 2) { return() }
+       
+     }
+   }
+ }
Error: no function to return from, jumping to top level
> 
> print(i)
[1] 5
> print(a)
[1] 7
> print(b)
[1] 2

Obviously far better and cleaner to use the function method.

EDIT:

Added an alternative solution to making the error look nicer given by Roland:

for (i in 1:10) {
  for (a in 1:10) {
    for(b in 1:10) {

      if (i == 5 & a == 7 & b == 2) { stop("Let's break out!") }

    }
  }
}

print(i)
print(a)
print(b)


来源:https://stackoverflow.com/questions/37571028/breaking-out-of-nested-loops-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!