How to use the next statement in a for loop in R

In R, the next statement skips an iteration without terminating the loop.

Remember that a for loop in R iterates over a sequence for a specific number of times. A conditional statement (the expression) within the for loop determines the number of iterations.

To declare a for loop in R, take a good look at its syntax below:

for(expression){
  statement(s)
}

In the syntax above, the expression represents the condition given. The statement represents what the code should execute, provided that the expression is TRUE.

The for loop is needed to repeat the same code until a particular condition is met.

Let’s see the examples below to better understand how the for loop works:

Simple for loop

for (x in 1:5) {
print(x)
}

Explanation

In the code above, we state the condition that R should print all values for x starting from 1 to 5 (these are the iterations).

Using the next statement

Without terminating the loop, we can skip a loop or an iteration using the next statement.

In the example below, we will create a list variable and use the next statement to skip an iteration at a specified item to another item in the list.

Skipping one iteration of the for loop

countries <- list("USA", "FRANCE", "UK", "CANADA", "CHINA")
for (x in countries) {
if (x == 'CANADA'){
next
}
print(x)
}

Explanation

In the code above, the loop will skip the list item, "CANADA". This is because we have chosen to skip the loop or iteration and move to another iteration by using the next statement when x is equal to "CANADA" (x == "CANADA").

Free Resources