R Tutorial R Charts & Graphs R Statistics R References

R - Break Statement



R Break statement

The break statement in R is used to terminate the program out of the loop containing it whenever the condition is met.

If the break statement is used in a nested loop (loop inside loop), it will terminate innermost loop after fulfilling the break criteria.

Break statement with While loop

In the example below, break statement is used to get out of the while loop if the value of variable j becomes 4.

j <- 0
while (j < 6){
  j <- j + 1
  
  #terminating the loop when j == 4
  if(j == 4) { 
    print("Getting out of the loop.")
    break
  }
  print(j)
}

The output of the above code will be:

[1] 1
[1] 2
[1] 3
[1] "Getting out of the loop."

Break statement with For loop

Here, the break statement is used to get out of the for loop if the value of variable x becomes "yellow".

color <- c("red", "blue", "green", "yellow", "black", "white")
for(x in color) { 
  #terminating the loop when x == "yellow"
  if(x == "yellow") {
    print("Getting out of the loop.")
    break
  }
  print(x)
}

The output of the above code will be:

[1] "red"
[1] "blue"
[1] "green"
[1] "Getting out of the loop."

Break statement with Nested loop

In the example below, break statement terminates the inner loop whenever multiplier becomes 100.

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

The output of the above code will be:

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

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

The output of the above code will be:

[1] "# nested loop with break statement"
[1] 10
[1] 20
[1] 30