next in R: Control the loop in R

In this article, we will show you how to use the next in R. The next is used to skip an iteration while working with the loop. Let’s learn which cases should use the next and how to use it with the explanation and examples below.

The next in R

What does the next do?

I think you learned about one of these languages before: C, C++, Java, or Python. These languages also have the 'continue' function to work with the loop. The next is the same function as the ‘continue’ method in other languages. The next can help you skip an iteration, and you do not make the loop terminate. The next and the break in R are used to control the loop.

Let’s learn how to use it in the next title below.

How to use the next in R?

We will show you what the next does with the for loop and while loop with two examples below.

Skip the iteration in the for loop

You can use the next to skip the iteration in the for loop without making the loop terminate.

# Create the list of the football players
players <- list("Ronaldo", "Messi", "Benzema", "Modric", "Maguire", "Giroud")

# Print all of the elements in this list without 'Maguire'
for (name in players) {
if (name == "Maguire") {
# Skip if the name is 'Maguire'
next
}
print(name)
}

Output

[1] "Ronaldo"
[1] "Messi"
[1] "Benzema"
[1] "Modric"
[1] "Giroud"

Skip the iteration in the while loop

You can use the next to skip the iteration in the while loop without making the loop terminate.

# Create the list of the countries in the semi-final of the World Cup 2022
countries <- list("Croatia", "France", "Argentina", "Maroc")

# Print all of the elements in this list without the index 3
iteration <- 0
while (iteration < length(countries)) {
iteration <- iteration + 1

if (iteration == 3) {
# Skip if the index is 3
next
}

print(countries[iteration])
}

Output

[[1]]
[1] "Croatia"

[[1]]
[1] "France"

[[1]]
[1] "Maroc"

Summary

We have shared with you what the next in R does and how to use it. The same function as the ‘continue’ method of other languages. The statement is used to skip an iteration of the loop without terminating it. If you have any questions about this guide, leave your comment below, and I will answer your questions. Thanks!

Maybe you are interested:

Posted in R