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

NNK

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply