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 isTRUE
.
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
.
The code below will execute (print x
) as long as x
is less than 6.
x <- 1while (x < 5) {print(x)x <- x + 1}
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.
next
statementIn 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 <- 0while (x < 5) {x <- x + 1if (x == 3) {next}print(x)}
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
).