Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

statement
r
break
communitycreator

How to use the break statement in R

Onyejiaku Theophilus Chidalu

Overview

A break statement in R stops a while loop from execution, even while the condition provided is TRUE.

Remember that a while loop executes a set of statements as long as the condition provided in the loop is TRUE.

The syntax for the while loop is written in the following way:

while(expression){
  print(statements)
  ---
}

For the statements provided to execute in the while loop, the expression given must be TRUE.

Example

The code below will execute (print x) as long as x is less than 6:

x <- 1
while (x < 6) {
  print(x)
  x <- x + 1
}
Implementing a while loop

The code above shows that the expression or condition provided was TRUE. This is because x was given an initial value of 1 and an increment of 1 for each execution until it gets to 5. This is the reason why the statement provided was executed. Otherwise, the statement of the loop will not run.

However, what if the while condition is TRUE, but you still want to stop the loop? This is where the break statement comes in.

break statement

Assuming you want to end the loop in the previous code before it gets to 3, you will need a break statement.

x <- 1
while (x < 5) {
  print(x)
  x <- x + 1
  if (x == 3) {
    break
  }
}

The loop will stop at 2 because we chose to finish the loop using the break statement when x becomes equal to 3 (x == 3).

RELATED TAGS

statement
r
break
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring