Break statement in R

break in r

Like other programming languages, the break statement is used to exit a loop in R. In this article, we will provide you with a few detailed examples of the break statement. If you have any confusion about the statement, do not miss this article.

The break statement in R 

The break statement is used with a condition inside a loop to interrupt the loop if the condition is true.

Syntax:

loop:

if(expression){

break

}

Parameters:

  • loop: A loop in R (repeat, for, while)
  • expression: A boolean expression

Some examples of using the break statement

Use the break statement inside a for loop

Suppose we have a list of numbers, and we want to find the value of the first number in the list greater than 10. In this case, we will traverse the list and compare each element with 10, and immediately break the loop if the number is greater than 10. Look at the following example.

Code:

# Declare a list
myList <- list(2, 4, 6, 1, 89, 12, 3.4, 22, 13, 4.87)

# Traverse the list and find the first number greater than 10
for (i in myList) {
    if (i > 10) {
        cat("The first number greater than 10 in the list is: ", i)
        break
    }
}

Result:

The first number greater than 10 in the list is: 89

Use the break statement inside a while loop

In this example, we will use the while loop to traverse from 0 to 7 and find numbers having squares smaller than 20. It means that we break the loop if the square is greater than 20.

Code:

# Initiate the value for x
x <- 0

# Find numbers having squares smaller than 20 in the range 0 to 7
cat("Numbers have the square smaller than 20 are:\n")
while (x < 7) {
    cat(x, " ")
    x <- x + 1
    if (x^2 > 20) {
        break
    }
}

Result:

Numbers have the square smaller than 20 are:
0 1 2 3 4 

Use the break statement inside a repeat loop

The repeat loop is a little bit different from the while loop. We will discover how to use the break statement inside a repeat loop. Take the same idea with the above example, we will use the repeat instead and see the result.

Code:

# Initiate the value for x
x <- 0

# Find numbers having square smaller than 20 in the range 0 to 7
cat("Numbers have the square smaller than 20 are:\n")
repeat{
    cat(x, " ")
    x <- x + 1
    if (x^2 > 20) {
        break
    }
}

Result:

Numbers have the square smaller than 20 are:
0 1 2 3 4 

Summary

In summary, the break statement is used with a boolean expression inside a loop and stops the loop if the condition is true. In this article, we have shown you examples of using the break statement with types of loops in R. We hope that you understand the flow of the process when using the break statement to avoid errors.

Maybe you are interested:

Posted in R

Leave a Reply

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