gpt4 book ai didi

r - 打破 R 中的嵌套循环

转载 作者:行者123 更新时间:2023-12-03 02:59:37 27 4
gpt4 key购买 nike

非常简单的示例代码(仅用于演示,没有任何用处):

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

我想从多个循环中跳出,而不是在每个循环中单独使用 break 。根据a similar question regarding python ,将循环包装到函数中似乎是一个可能的解决方案,即使用 return() 打破函数中的每个循环:

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

nestedLoop()
print("finished")

R 中还有其他可用的方法吗?也许类似于标记循环,然后指定要中断哪个循环(就像在 Java 中一样)?

最佳答案

使用显式标志,并根据这些标志有条件地跳出循环可以提供更多灵 active 。示例:

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 的情况。这种结构很容易使用,并且非常灵活。

关于r - 打破 R 中的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37571028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com