R Tutorial R Charts & Graphs R Statistics R References

R - Next Statement



The next statement in R let the program skip a block of codes for current iteration in a loop. Whenever next statement condition is fulfilled, it brings the program to the start of loop.

When the next statement is used in a nested loop (loop inside loop), it will skip innermost loop's code block, whenever condition is fulfilled.

Next statement with While loop

In the example below, next statement is used to skip the while loop if the value of variable j becomes 4.

j <- 0
while (j < 6){
  j <- j + 1
  
  #skip the loop when j == 4
  if(j == 4) { 
    print("this iteration is skipped.")
    next
  }
  print(j)
}

The output of the above code will be:

[1] 1
[1] 2
[1] 3
[1] "this iteration is skipped."
[1] 5
[1] 6

Next statement with For loop

In the example below, next statement is used to skip the for loop if the value of variable x becomes "yellow".

color <- c("red", "blue", "green", "yellow", "black", "white")
for(x in color) { 
  #skip the loop when x == "yellow"
  if(x == "yellow") {
    print("this iteration is skipped.")
    next
  }
  print(x)
}

The output of the above code will be:

[1] "red"
[1] "blue"
[1] "green"
[1] "this iteration is skipped."
[1] "black"
[1] "white"

Next statement with Nested loop

The next statement skip the inner loop's block of codes whenever condition is fulfilled. In below mentioned example, program skips the inner loop for multiplier = 100.

# nested loop without next statement   
digits <- c(1, 2, 3) 
multipliers <- c(10, 100, 1000)
print("# nested loop without next statement")
for (digit in digits)
  for (multiplier in multipliers)
    print (digit * multiplier)

The output of the above code will be:

[1] "# nested loop without next statement"
[1] 10
[1] 100
[1] 1000
[1] 20
[1] 200
[1] 2000
[1] 30
[1] 300
[1] 3000

# nested loop with next statement   
digits <- c(1, 2, 3) 
multipliers <- c(10, 100, 1000)
print("# nested loop with next statement")
for (digit in digits) {
  for (multiplier in multipliers) {
    if (multiplier == 100) 
      next
    print (digit * multiplier)
  }
}

The output of the above code will be:

[1] "# nested loop with next statement"
[1] 10
[1] 1000
[1] 20
[1] 2000
[1] 30
[1] 3000

5