Learn About Loops In R

Introduction

 
In this article, we will learn how to repeat the execution of certain parts of R code using loops. In some cases, there is a need to execute a section of code for a number of times. Loops can help you achieve this effectively. Generally, loops execute the statements according to the order they have been written.
 

Different Loops in R

 
R supports different types of loop statements. Let us discuss them.
 
repeat Loop
 
With this loop, a piece of code will be executed again and again until it finds a stop condition. The repeat loop does not have a condition to check so as to exit the loop. We have to explicitly add the condition inside the loop body and use the break statement so as to exit the loop. If we don’t do so, we will have created an infinite loop.
 
The repeat loop in R takes the following syntax,
  1. repeat {  
  2. commands  
  3. if(condition) {  
  4. break  
  5. }  
  6. }  
Consider the example given below which shows how this loop can be used,
  1. > msg <- c("Hello","World!")  
  2. > count <- 2  
  3. > repeat {  
  4. print(msg)  
  5. + count <- count+1  
  6. if(count > 5) {  
  7. break  
  8. + }  
  9. + }  
Write the script in an r script file and execute it from the terminal of your OS. it will return the following output,
  1. [1"Hello"  "World!"  
  2. [1"Hello"  "World!"  
  3. [1"Hello"  "World!"  
  4. [1"Hello"  "World!"  
We have created two variables, msg, and count. The first one has a list of strings while the second variable holds the integer 2. Inside the body of the repeat loop, we are trying to print the value of msg variable. The counting will begin at number 2 because the value of variable count was initialized to 2. We have used the if statement to create a condition.
 
The condition will ensure that the value of variable count does not go beyond 5. The loop will iterate from 2 to 5, meaning that the value of msg variable will be printed for only 4 times. That is how we got the above output! If it were not for the condition inside the if statement, the loop would run forever. 
 
Here is another example,
  1. > y <- 1  
  2. > repeat {  
  3. print(y)  
  4. + y = y+1  
  5. if (y == 5){  
  6. break  
  7. + }  
  8. + }  
The script will return the following upon execution,
  1. [11  
  2. [12  
  3. [13  
  4. [14  
We initialized the value of variable y to 1. In the if condition, we are checking for when the value of this variable is 5, at which the loop should stop. That is why the loop printed values only between 1 and 4, with 4 included.
 
While Loop
 
This type of loop will execute code again and again until it meets a particular condition. The loop takes the syntax given below,
  1. while (test_expression) {  
  2. statement  
  3. }  
The test_expression will be evaluated first before getting into the loop body. If the test_expression is true, the loop body will be executed. After execution of the loop body, execution will return to the test_expression. If true, the loop body will be executed again. With such a syntax, the loop might end up not running. If the test_expression is found to be false for the first time, the loop will have to be skipped, and then the statement that occurs immediately after the loop body will be executed.
 
Consider the example given below,
  1. > msg <- c("Hello","this is a while loop")  
  2. > count <- 2  
  3. while (count < 6) {  
  4. print(msg)  
  5. + count = count + 1  
  6. + }  
The script should return the following result,
  1. [1"Hello"                "this is a while loop"  
  2. [1"Hello"                "this is a while loop"  
  3. [1"Hello"                "this is a while loop"  
  4. [1"Hello"                "this is a while loop"  
Here is another example that demonstrates the use of the while loop,
  1. > y <- 1  
  2. while (y < 6) {  
  3. print(y)  
  4. + y = y+1  
  5. + }  
The script will return the following output upon execution,
  1. [11  
  2. [12  
  3. [13  
  4. [14  
  5. [15  
The code returns numbers from 1 to 5.
 
For Loop
 
This is a repetition control structure that helps R programmers to write a loop that executes a particular section of code for a specific number of times.
The statement takes the basic syntax given below,
  1. for (value in vector) {  
  2. statements  
  3. }  
The for loop is very flexible since it is not limited to numbers or integers as the input. We can pass logical vectors, character vectors, and expressions or lists to it.  
Consider the example given below,
  1. > l <- LETTERS[1:5]  
  2. for ( j in l) {  
  3. print(j)  
  4. + }  
Execution of the above program will return the following output,
  1. [1"A"  
  2. [1"B"  
  3. [1"C"  
  4. [1"D"  
  5. [1"E"  
We have created a variable l. The LETTERS is an R keyword which represents all letters of the alphabet from A to Z, uppercase. The variable l will store the first 5 letters, that is, from A to E. We have then used a for loop to iterate through these. We have lastly printed them on the terminal.
 
Here is another example,
  1. > y <- c(3,5,2,9,7,11,4)  
  2. > count <- 0  
  3. for (val in y) {  
  4. if(val %% 2 == 0)  
  5. + count = count+1  
  6. + }  
  7. print(count)  
The script will return the following output upon execution,
  1. [12  
  2. >  
We have created a vector y with a number of integers. The variable count has been initialized to 0. Inside the for loop, we have created the variable val to help us iterate the elements of the vector. We have used the if statement to check whether there are even numbers inside vector y. An integer is an even number if it gives a remainder of 0 after division by 2. The count variable helps us count the number of even numbers found inside the vector. From the output, only 2 even numbers were found.
 

Summary

 
In this article, I demonstrated how to repeat the execution of certain parts of R code using loops statements. I explained each and every loop statements such as for and while loop statements in detail. Proper coding snippets as well as outputs are also provided.