What are break and next statements in R?
Overview
Loops are worth using when performing iterations. But what if we want to skip something in a loop or end a loop earlier than the complete execution?
R language provides this facility to the programmers with break and next statements. These predefined keywords are used to either terminate the iteration or skip the program for a certain iteration inside the loop and execute the next one.
break statement
The break statement is used to terminate the loop earlier than the ending iteration. It breaks the loop at a particular iteration.
Syntax
Loop(condition){ # While Loop can either for or whilebreak}
Explanation
Let's elaborate break statement in R with proper examples in different conditions.
break statement in for loop:
# using break statement# creating a vectorm <- 1:9# iterating through vectorfor (val in m) {if (val == 6) {break}print(val)}
break statement is used in line 7 inside the if condition. It indicates to terminate the for loop when the value is equal to 6. This print the values from 1 to 5 and exit the loop.
break statement in while loop:
Let's use break statement in the while loop:
# creating vectorm <- 5# while loopwhile (m < 15) {print(m)if(m==11) # condition to meetbreakm = m + 1}
Loop(condition){if(any_test_condition) {next}}
Explanation
Let's elaborate next statement in R with proper examples in different conditions.
next statement in for loop:
# Creating a vector containing values from 1 to 8mydata <- 1:8for (val in mydata) {if (val == 4) {print(paste("Skipping for loop on:", val))next}print(paste("My values are:", val))}
mydata <- 2while(mydata < 8) {mydata <- mydata + 1;if (mydata == 4)next;print(mydata);}