R Programming language - R break and next

In R programming language, break and next are control flow statements that can be used inside loops to alter the flow of the loop.

break statement:
The break statement is used to exit a loop prematurely. When executed, the break statement will immediately terminate the innermost loop in which it is located. Here is an example of a for loop that uses the break statement:

for (i in 1:10) {
  if (i == 5) {
    break
  }
  print(i)
}
Source:‮www‬.theitroad.com

In this example, the loop will iterate from 1 to 10, but when i equals 5, the if statement inside the loop executes the break statement, which immediately exits the loop. The output of this code will be:

[1] 1
[1] 2
[1] 3
[1] 4

next statement:
The next statement is used to skip over an iteration of a loop. When executed, the next statement will skip the remaining statements in the current iteration of the loop and move on to the next iteration. Here is an example of a for loop that uses the next statement:

for (i in 1:10) {
  if (i %% 2 == 0) {
    next
  }
  print(i)
}

In this example, the loop will iterate from 1 to 10, but when i is an even number (i.e., when i is divisible by 2), the if statement inside the loop executes the next statement, which skips the remaining statements in the current iteration of the loop and moves on to the next iteration. The output of this code will be:

[1] 1
[1] 3
[1] 5
[1] 7
[1] 9

Both the break and next statements can be used with any type of loop in R, including for, while, and repeat loops. They are useful for controlling the flow of the loop based on specific conditions.