Break Statement in R

R break statement is used to break a loop prematurely. The loop could be R repeat loop, R while loop or R for loop.

Syntax

The syntax of break statement is

</>
Copy
break

Execution Flow Diagram

The flow of execution in a loop with break statement is depicted in the following flow diagram.

R Break Statement

Break statement is kept in the if block with breaking condition. When break condition is met, the loop is broken, execution flow comes out of the loop and continues with the statements after loop statement.

Example 1 – R Break statement

We shall see some examples using break statement for different loop statements in R programming language.

r_loop_break.R

</>
Copy
# R for loop

a = c(2, 45, 9, 12)
print("break for loop")

for(i in a) {
	if(i==9){
		break
	}
	print(i)
}

# R while loop

a = 1
b = 4
print("break while loop")

while(a<5) {
	print(a)
	a = a+1
	if(b+a >6){
		break
	}
}

# R repeat statement

a = 1
print("break repeat loop")

repeat {
	print(a)
	a = a+1
	if(a>6){
		break
	}
}

Output

$ Rscript r_loop_break.R 
[1] "break for loop"
[1] 2
[1] 45
[1] "break while loop"
[1] 1
[1] 2
[1] "break repeat loop"
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6

Conclusion

In this R Tutorial, we have learnt break statement and how to use it to break loops prematurely.