103
votes

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?

2
Instead of skipping when a condition is met, you should not skip when a condition is not met--for(n in 1:5){if(n!=3){cat(n)}}MichaelChirico

2 Answers

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

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) }