R break statement

In the R programming language, the break statement is used within loops (such as for and while loops) to prematurely exit the loop and continue with the execution of the code after the loop. When the break statement is encountered, the loop immediately terminates, even if the loop condition or iteration count is not met.

Here’s an example of how the break statement works in R:

for (i in 1:10) {

  if (i == 5) {

    break

  }

  print(i)

}

print(“Loop finished”)

In this example, the for loop iterates from 1 to 10. Inside the loop, there’s an if statement that checks if i is equal to 5. When i becomes 5, the break statement is executed, and the loop terminates immediately. As a result, only values from 1 to 4 will be printed, and “Loop finished” will be printed after the loop.

Here’s the output of the above code:

[1] 1

[1] 2

[1] 3

[1] 4

[1] “Loop finished”

So, the break statement is useful when you want to exit a loop prematurely based on a certain condition.

Leave a Comment

Your email address will not be published. Required fields are marked *