R for loop skip to next iteration ifelse

RFor Loop

R Problem Overview


Suppose you have a for loop like so

for(n in 1:5) {
  #if(n=3) # skip 3rd iteration and go to next iteration
  cat(n)
}

How would one skip to the next iteration if a certain condition is met?

R Solutions


Solution 1 - R

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Solution 2 - R

If you want jump out of the loop, like that:

for(n in 1:5) { if(n==3) break # jump out of loop, not iterating cat(n) }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalkiView Question on Stackoverflow
Solution 1 - RAlexey FerapontovView Answer on Stackoverflow
Solution 2 - ROthon OliveiraView Answer on Stackoverflow