How to use the next statement in R

Overview

We can use a next statement in R to skip a while loop iteration without terminating the loop.

A while loop is used to execute a set of statements as long as the provided condition is TRUE.

The syntax for a while loop is as shown below:

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

For the statement to execute in the while loop, the expression must be true.

Example

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

x <- 1
while (x < 5) {
print(x)
x <- x + 1
}

Explanation

In the code above, we can see that the expression or condition is true because x is given an initial value of 1 and an increment of 1 for each execution until it gets to 5. If otherwise, the statement will not execute.

If you wanted to skip the value of 2 and move to the next iteration without terminating the loop in the code above, you would use the next statement.

The next statement

In the code below, we want to skip the value of x == 2 and move to the next iteration, so we use the next statement.

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

Explanation

In the code above, we use the next statement to skip the value x == 3 and proceed to the next iteration (i.e. x == 4).