Rob*_*tix 6 loops for-loop r break while-loop
非常简单的示例代码(仅用于演示,完全不使用):
repeat {
while (1 > 0) {
for (i in seq(1, 100)) {
break # usually tied to a condition
}
break
}
break
}
print("finished")
Run Code Online (Sandbox Code Playgroud)
我想从多个循环break中分离而不分别在每个循环中使用.根据关于python的类似问题,将我的循环包装到函数中似乎是一种可能的解决方案,即使用return()突破函数中的每个循环:
nestedLoop <- function() {
repeat {
while (1 > 0) {
for (i in seq(1, 100)) {
return()
}
}
}
}
nestedLoop()
print("finished")
Run Code Online (Sandbox Code Playgroud)
R中还有其他方法吗?也许类似于标记循环然后指定要中断的循环(如在Java中)?
使用显式标志,并在这些标志上有条件地断开循环可以提供更多的灵活性.例:
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
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将打破两个嵌套循环i=3.当最后一行(if (stop){break})被注释掉时,只有内部循环被破坏i=3,但外部循环继续运行,即它实际上跳过了这种情况i=3.这种结构易于使用,并且可以根据需要灵活使用.
我认为您将嵌套循环包装到函数中的方法是最干净且可能是最好的方法。你实际上可以在全局环境中调用return(),但它会抛出错误并且看起来很难看,如下所示:
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)
Run Code Online (Sandbox Code Playgroud)
在命令行中看起来像这样:
> 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
Run Code Online (Sandbox Code Playgroud)
显然使用函数方法要好得多、更干净。
编辑:
添加了 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)
Run Code Online (Sandbox Code Playgroud)