Repeat Loop in R

R Repeat Loop does the execution of a set of statements in a loop until a break condition is met. In this R Tutorial, we shall learn Repeat Loop syntax and execution flow with Example R Scripts.

Syntax – R Repeat Loop

The syntax of Repeat Loop in R is

</>
Copy
repeat {
      statements
      if(stop_condition) {
          break
      }
  }

Execution Flow

Following picture depicts the flow of execution in and around the repeat loop statement.

R Repeat Loop

Breaking Condition

Breaking is done using an R if statement.

It is optional. But if you do not place a breaking condition in the repeat loop statement, the statements in the repeat block will get executed for ever in an infinite loop.

Breaking Condition should return a boolean value, either TRUE or FALSE.

The placement of breaking condition is up to the developer. You may keep it before the “block of statements” block or after it.

Example 1 – R Repeat Loop

In this example, we will write a repeat loop that executes until the breaking condition becomes true.

r_repeat_loop_ex.R

</>
Copy
# R Repeat Loop statement Example

a = 1

repeat {
	# starting of repeat statements block
	print(a)
	a = a+1
	# ending of repeat statements block
	if(a>6){	# breaking condition
		break
	}
}

Output

$ Rscript r_repeat_loop_ex.R 
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6

Conclusion

In this R Tutorial, we have learnt Repeat Loop, its Syntax and Execution Flow with Example R Scripts.