Loops In R With Examples - For, While & Repeat Loops

In our previous tutorial, we learned conditional statements in controlling the structure of the R program like if, if-else, nested else if, switch statements, etc to control the flow of the R program. In this tutorial also another mode of control structure to control the flow of execution in the R program is going to discuss which is known as looping. These are similar to the control structures in other programming languages like C, PYTHON, etc. These control structures are very useful when dealing with data analysis or writing a function in R.

What are loops in R?

In R programming language loop is a fundamental concept. Loops in the programming language are repeating routines and subroutines in our everyday life. Everybody's daily routine is preparing tea. In computer language, these procedures can be stored as instructions to execute whenever called by making a function. These functions can be executed over and over again by using the loops. It is better to practice the reuse of these repeating routines by putting them inside a function.

The words “looping”, and “iteration” are commonly used with loops control structure which generally means grouping or batching a set of repeating the process (execution of same code) or organizing similar actions that need to be performed multiple times into a single structure.

When you want to repeat a function or body of statements multiple times it is better to use a loop which saves time. The concept of loop is similar in all programing languages they do differ only in terms of their syntax.

  • A loop allows to continuously execute a block of code multiple times.
  • There are certain conditions defined with loops for their execution.
  • A loop continues its execution until a stopping condition is met with and the control moves out of the loop.
loops img

There are mainly three types of loops in R: - for-loop, while loop, and repeat loop.

  • The for loops are special control flow constructs where execution occurs for a predefined number of times by setting a counter or index that gets incremented during the iteration cycle.
  • The while or repeat belongs to a looping structure that needs validating a logical condition. After the verification of the condition, either at the beginning or end of the loop construct only the execution begins else it gets terminated.

In the R documentation, you can see along with for loop, while loop, repeat loop there are some additional control flow structures like a break, next, etc

When working with large datasets the use of loops is sometimes inefficient in R . In such cases you can make use of the family of apply() functions like apply(), lapply(), tapply(), sapply(), vapply(), and mapply().

NOTE: You can use apply function family instead of for loop.

for loop in R

In R programming language the concept of for loop is the same as they do in any other programming language.

The for loops are special control flow constructs where execution occurs for a predefined number of times by setting a counter or index that gets incremented during the iteration cycle.

When you want to iterate over a range or series of data the most simple and easy to use is the loops. During each iteration, the value is stored inside a variable known as the iterator variable.

Syntax


for(variable in sequence){
    #perform some instructions
}

Where

  • variable is the iterator variable
  • sequence  represents  the range through which looping has to do
  • The curly braces enclose the codes to execute during each iteration.

Consider a simple for loop


#for loop in R
for(i in 1:10){
  print(i)
}

The for-loop example displays the range of numbers from 1 to 10. The value in the range 1:10 (1, 2, 3, 4, 5, 6, 7, 8, 9, and 10) is stored during each iteration time to the variable a. The variable i is the iterator variable. The for loop starts with executing i=1and prints the value of i, i.e. 1 in the console. Then takes the next value which stores i=2, displays the value during i is equal to 2. So on the execution continues till it reaches or takes up the last value mentioned in the range. In our example when i=10 has displayed the execution of for-loop exits from iteration.

The flow chart of for loop makes our understanding much easier.

for loop flowchart

From this example, it is very clear that in looping same instruction is executed multiple times over a different set of values.

Let us check another example that takes string character input by creating a vector using the c() function.


#vector v with 5 character values
v<-c("Learn","eTutorials","for","R","Program") 

for(i in 1:5){
  print(v[i])
}

The for-loop iterates over each character in vector input v.The variable iterator i hold the value at the 1st position of vector v i.e. “Learn”.So when i=1 during the execution of for loop, it accesses and displays the first element of vector v in the console v[1] = “Learn”.In the subsequent iterations, the value of the iterator variable i keep on changing like 2,3,4,5. And each time respective elements from the vector are accessed and displayed like v[2] = "eTutorials", v[3] = "for", etc.. Look at the below output of the same code.


[1] "Learn"
[1] "eTutorials"
[1] "for"
[1] "R"
[1] "Program"

The range (1:5) inside the for-loop can be altered using seq_along(), which outputs the same result.


v<-c("Learn","eTutorials","for","R","Program") 

for(i in seq_along(v)){
  print(v[i])
}

The seq is to generate regular sequences is a standard generic with a default method. seq_along is a primitive. The syntax is seq_along(along.with) which takes the length from the arguments passed into it.

In our example, the input vector v is passed to the method seq_along which takes up the length from the length of arguments which is equal to 5. The method generates the sequence in which elements (character) in vector v.Thus for loop use this method in iteration similar to range() function.

The snippet from RStudio showing details of seq() and seq_along() description is attached below

for loop snippet

Nested for loop

An example to show nested for loop. A for-loop inside another for-loop is meant by a nested for loop. Let us start with an example.

  1. Create a matrix MAT. (recall the tutorial matrix) A 2×3 matrix of elements ranging from 1 to 6 with two rows and three columns is created using the matrix() function.

     

    
    > MAT = matrix(1:6,2,3)
    > MAT
         [,1] [,2] [,3]
    [1,]    1    3    5
    [2,]    2    4    6
    
    
  2. Create a nested for loop that prints each row and column element inside the matrix. Notice here we use seq_len() to generate the sequence which takes the desired length of the arguments passed through it.The seq_len(nrow(MAT)) produces a sequence of 1 2 of rows and seq_len(ncol(MAT)) produces a sequence 1 2 3 of columns
    
    
    #NESTED for-loop
    for(i in seq_len(nrow(MAT))){            #i=1,2 nrow(number of rows of matrix) 
     #2 times loop iterates
    
      for(j in seq_len(ncol(MAT))){           #j=1,2,3 ncol(number of matrix column )(3times iterates)
        print(MAT[i,j])
      }
    
    }
    
    

Let us see the full source code in the R program for looping in a matrix to print all elements inside a matrix.

nested for loop img

The picture shows the working of nested for loop, when the first for loop for(i in seq_len(nrow(MAT))) begins its execution value of I will be 1,takes first row and next for loop for(j in seq_len(ncol(MAT))) takes the number of columns sequence as j=1,2,3.when i=1 and j=1 access the first element of the matrix 1.Repeats the same for when i=1,j=2 and i=1 ,j=3 to complete the iteration.

Similary works for the next row when i=2 displays matrix elements by looping over columns j=1,2,3.


#create a 2×3 matrix 
MAT =matrix(1:6,2,3)
cat("The matrix MAT is \n")
print(MAT)

#NESTED for-loop
cat("The elements of matrix is \n")
for(i in seq_len(nrow(MAT))){            #i=1,2 nrow(number of rows of matrix)
  for(j in seq_len(ncol(MAT))){          #j=1,2,3 ncol(number of matrix column )
    print(MAT[i,j])
  }
}

The output generated by the nested for loop is


> rep(Vector1,times =3)
[1]  5 45 19  5 45 19  5 45 19
> rep.int(Vector1,times =3)
[1]  5 45 19  5 45 19  5 45 19
>

While loop in R

In R programing language, the while loop is another major looping construct. The while loop takes a logical expression and executes the loop based on the validation of the logical expression. If the expression or condition is true the block of codes inside it will get executed else in other cases will not execute.

The while is also a reserved word to denote the basic control flow structure.

Syntax


While(condition){
     #perform some instructions
}

Where

  • condition is the expression to validate as TRUE or FALSE
  • If TRUE executes the codes given inside curly braces.

Example


#while loop

i=1
while(i<=10){
  print(i)
  i=i+1
}

The output generated is a sequence of numbers from 1 to 10. The execution terminates when the iterator variable i become 10. The condition fails to satisfy if i is incremented further. When i=11 (i=10+1) checks the condition (i<=10) where 11 is not less than 10 .Here condition becomes FALSE and exits from the loop.


[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Flowchart of while loop

while loop flowchart

The for-loop and while loop both have similar manner functionality. But they do differ from each other based on the following reasons:

  • While loop always contains an iterator variable defined prior to the running loop. But in for loop no such initialization of iterator variables is needed.

    For example consider the simple code to display numbers 1 to 10 where the value of the iterator variable(i) is initialized to 1, ie i=1 prior to the while loop execution.

    
    #while loop
    i=1
    while(i<=10){
      print(i)
      i=i+1
    }
    
    
  • In the while loop whenever the codes have been executed the condition is checked first which is different from the for-loop. In for-loop, the condition is checked only at the end of the loop body, in while loop the condition is checked at the beginning of the loop body.
  • The iterator variable needs to be incremented each time in the while loop.

    The above code to display a range of numbers from 1, 2, 3 …10 has an incrementation of the iterator variable i by the instruction i=i+1. If i=i+1 is not provided the while loop ends up displaying the initial value in the range over infinite times.

So you can summarize that in the while loop there need to initialize and increment the iterator variable(i)

NOTE: Generally, when we compare the differences the for-loop is more efficient than the while loop.

Repeat in R

A repeat loop allows the execution of any block of code a repeated number of times. Like in other control structures a repeat loop does not have any conditions to be satisfied for its successful execution and thus to exit or terminate from any loop.

The programmer is responsible for providing an exit condition inside the control structure (maybe a for loop, while loop) to exit from the execution otherwise it results in infinite looping. Usually, a break statement inside the control structure enables the termination of the infinite execution to avoid the repetition of the same code.

Syntax


repeat { 
 #  instruction to execute
   ....
   .... 
   if(condition) {
      break
   }
}

Flowchart of the repeat loop

repeatloop flowchart

Program using repeat statements


x = 5
  
# Print 5 to 10
repeat{
  print(x)
  x = x + 1
  if(x > 10){
    break
   }
}

The output produced shows that the break statement interrupts the execution from repeating the execution of the given block of codes.


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

Now we have an idea about the loops in R programming. In the coming tutorial, we are going to learn about the jump statements which we use in the loop like a break, next, etc. in detail.