In this tutorial, we will learn about the break statement in R. We will cover the basics of using the break statement to exit loops prematurely.
A break statement is used to terminate the execution of a loop. When a break statement is encountered, control is transferred to the statement immediately following the loop.
The syntax for the break statement in R is:
break
The break statement can be used in for, while, and repeat loops to exit the current loop prematurely.
i
is equal to 5.i
.for (i in 1:10) {
if (i == 5) {
break
}
print(i)
}
[1] 1 [1] 2 [1] 3 [1] 4
i
and initialize it to 1.i
is less than or equal to 10.i
is equal to 5.i
.i <- 1
while (i <= 10) {
if (i == 5) {
break
}
print(i)
i <- i + 1
}
[1] 1 [1] 2 [1] 3 [1] 4
i
and initialize it to 1.i
is equal to 5.i
.i <- 1
repeat {
if (i == 5) {
break
}
print(i)
i <- i + 1
}
[1] 1 [1] 2 [1] 3 [1] 4