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) ?
Next and Break Statements in R A break statement is used inside a loop (repeat,for,while) to stop the iterations and control flow within a loop. In other words, the break statement will stop executing the block of instructions within a loop and exit the loop.
There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.
The R Break statement is very useful to exit from any loop such as For, While, and Repeat. While executing these, if R finds the break statement inside them, it will stop executing the code and immediately exit from the loop.
Originally Answered: How can I avoid nested "for loop" for optimize my code? Sort the array first. Then run once over it and count consecutive elements. For each count larger than 1, compute count-choose-2 and sum them up.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With