R: repeat - break - next
I. break statement
The break statement is used inside a loop to permanently stop the loop from cycling through the code. In other words, once the break statement is used, the the flow of the program exits the loop.
> for(i in 1:10)
+ {
+ print(i)
+
+ # THIS WILL STOP THE LOOP WHEN i IS EQUAL TO 6
+ if(i == 6){ break }
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
>
II. next statement
The next statement will force the program to stop working on the current loop and move onto the next loop.
> for(i in 1:5)
+ {
+ # WILL FORCE LOOP TO MOVE ONTO NEXT ITERATION WHEN i EQUALS 3
+ if(i == 3){ next }
+
+ print(i)
+ }
[1] 1
[1] 2
[1] 4
[1] 5
>
III. repeat loop
The repeat loop, does exactly as the name implies, it keeps repeating code over and over until it is told to stop. It is important to note that one needs to use the break statement to exit the loop, as shown below. If the break statement is not used or not triggered, the loop will continue indefinitely.
> x = 1
>
> repeat
+ {
+ print(x)
+ x = x + 1
+
+ # THIS WILL STOP THE LOOP WHEN x IS EQUAL TO 6
+ if(x == 6){ break }
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
>
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.