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:
for
loopfor (x in 1:5) {print(x)}
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).
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.
for
loopcountries <- list("USA", "FRANCE", "UK", "CANADA", "CHINA")for (x in countries) {if (x == 'CANADA'){next}print(x)}
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"
).