Repeat, Next, Break in R

repeat loop in R:

A repeat loop is used to iterate over a block of code multiple number of times. There is no condition check in repeat loop to exit the loop. The only way to exit a repeat loop is to call break. These are not commonly used in statistical or data analysis applications but they do have their uses.

Syntax of repeat loop:

repeat {
      R Code

      if(…){
         R Code
         break
     }
}

Example:

 

x <- 5

repeat {
print(x)
x = x+1
if (x == 10){
break
}
}

Output:

[1] 5
[1] 6
[1] 7
[1] 8
[1] 9

Another Example:

 

set.seed(1)

repeat {
x<-runif(1, 5, 10)
print(x)
if(x < 6){
break
}
}

Output:

[1] 6.327543
[1] 6.860619
[1] 7.864267
[1] 9.541039
[1] 6.00841
[1] 9.491948
[1] 9.723376
[1] 8.303989
[1] 8.14557
[1] 5.308931

next and  break in R:

 

Example of next:

for(i in 1:10) {

if(i <= 5) {
# Skip the first 5 iterations
next
}
print(i)
}

Output:

[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Example of break:

 

for(i in 1:100) {
print(i)
if(i > 3) {
print(i)
# Stop loop after 3 iterations
break
}
}

Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 4

While loops

Loop Functions