You are currently viewing Repeat Loop in R

The repeat loop statement in R is similar to do while statement in other languages. repeat run the block of statements repeatedly until the break jump statement is encountered. You have to use the break statement to terminate or exit the loop. Not using a break will end up the repeat statement in an indefinite loop.

This statement is mostly used if you wanted to execute the repeated block at least one time.

Below is a flow chart of how the repeat statement works.

repeat loop in r

1. repeat of Syntax

The following is the syntax of the repeat statement


# repeat syntax
repeat 
{ 
   #one or more statements
 
   if( condition ) 
   {
      break
   }
}

2. repeat Loop Example

Let’s understand the repeat loop statement with an example in R.


# repeat example
i = 1
repeat {
  print(i)
  i = i + 1

  if(i >= 5 )
    break
}

# Output
#[1] 1
#[1] 2
#[1] 3
#[1] 4

Conclusion

In this article, you have learned what is repeat loop statement in R and how to use it with an example. The repeat loop statement in R is similar to do while statement in other languages. repeat run the block of statements repeatedly until the break jump statement is encountered. You have to use the break statement to terminate or exit the loop. Not using a break will end up repeat statements in an indefinite loop.

Related Articles

References

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium