Skip for-Loop to Next Iteration in R (Example)

 

In this article you’ll learn how to stop the currently running iteration of a loop and move on to the next iteration in the R programming language.

The article consists of one example for the skipping of iterations in loops. To be more specific, the article is structured as follows:

Let’s jump right to the example.

 

Example: Skipping Certain Iterations of for-Loop

The following syntax illustrates how to move to the next iteration in case a certain if-statement is TRUE. Let’s first create a basic for-loop in R:

for(i in 1:10) {        # Regular for-loop
  cat(paste("Iteration", i, "was finished.\n"))
}
# Iteration 1 was finished.
# Iteration 2 was finished.
# Iteration 3 was finished.
# Iteration 4 was finished.
# Iteration 5 was finished.
# Iteration 6 was finished.
# Iteration 7 was finished.
# Iteration 8 was finished.
# Iteration 9 was finished.
# Iteration 10 was finished.

As you can see based on the previous output of the RStudio console, our for-loop returns the sentence “Iteration i was finished.” whenever an iteration runs until the end.

Now, let’s implement an if-condition, which sometimes stops the currently running iteration. For this task, we can use the next function as shown below:

for(i in 1:10) {        # for-loop containing next function
 
  if(i %in% c(2, 5, 8)) next
 
  cat(paste("Iteration", i, "was finished.\n"))
}
# Iteration 1 was finished.
# Iteration 3 was finished.
# Iteration 4 was finished.
# Iteration 6 was finished.
# Iteration 7 was finished.
# Iteration 9 was finished.
# Iteration 10 was finished.

Compare this output with the previous output. As you can see, the iterations 2, 5, and 8 were skipped.

Note that we could apply this R code to different types of loops such as for-loops or while-loops.

 

Video, Further Resources & Summary

Some time ago I have published a video on my YouTube channel, which shows the R programming syntax of this article. You can find the video below.

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

In addition, you might have a look at the related articles on my website:

 

In summary: In this article you learned how to skip an iteration in case an if-condition is fulfilled in the R programming language. In case you have any additional questions, let me know in the comments below.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top