突破R中的嵌套循环 [英] Breaking out of nested loops in R
问题描述
非常简单的示例代码(仅用于演示,根本不使用):
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")
我想从多个循环中脱颖而出,而不必在每个循环中分别使用break
.
根据关于python的类似问题,将我的循环到一个函数中似乎是一种可能的解决方案,即使用return()
打破该函数中的每个循环:
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")
R中还有其他可用的方法吗?也许像标记循环之类的,然后指定要中断的循环(例如在Java中)?
Are there other methods available in R? Maybe something like labeling loops and then specifying which loop to break (like in Java) ?
推荐答案
使用显式标志,并有条件地打破这些标志的循环,可以提供更大的灵活性.示例:
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
}
当i=3
时,上面的代码将打破两个嵌套循环.当最后一行(if (stop){break}
)被注释掉时,只有内部循环在i=3
处断开,但外部循环继续运行,即实际上跳过了i=3
的情况.这种结构易于使用,并且可以根据需要灵活地进行.
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.
这篇关于突破R中的嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!