R Loops

Loops are used to repeat a certain set of actions so you don’t have to perform them repeatedly. Suppose you want to perform operation 10 times, if you start writing the code for each time, the program’s length increases and it would be difficult for you to understand it later. But you can remove this problem by using a loop, by writing the same statement inside a loop; it will save time and makes easier for code reliability.

R language has the following kinds of a loop:

Repeat

Repeat loop is used to execute the same block of code again and again until a stop condition is met.

Syntax:

Flow Chart:

R Repeat

 

 

 

 

 

 

 

 

 

Example:

Output:

While loop

While loop is also used to execute the same block of code again and again until a break condition is met.

Syntax:

Flow Chart:

R while loop

 

 

 

 

 

 

 

 

 

 

 

Example:

Output:

The main difference between repeat and while loop is that while tests a condition to define when to finish looping, but repeat requires you to explicitly break the loop on your own and which can be at any point in the body of the loop. Depending on where you put your break statement.

For loop

For loop is used to iterate over a list of elements or a range of numbers. Loop can be used to iterate over a data frame, vector, list, matrix or any other object.

Syntax:

Flow Chart:

R for loop

 

 

 

 

 

 

 

 

 

 

 

Example:

Output:

 

Break Statement

In R programming language break statement has the following two usages:

  • The break statement is used to terminate the program and resumes the control to the next statement following the loop.
  • The break is also used to terminate a case in the switch statement.

Syntax:

Flow Chart:

R Break

 

 

 

 

 

 

 

 

 

Example 1:

Output:

Example 2:

Output:

Next Statement

A next statement is used to skip the current iteration of the loop without terminating it. It is similar to continue statement in other programming languages.

Syntax:

Flow Chart:

R Next

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Example 1:

Output:

Example 2:

Output: