Loops In R

In my previous article, I described "If Else Statement in R". This article will take you a step further. This article is about loops in R. If you are completely new to the R language, then please read "Introduction to R and RStudio". 
 

What is a loop?

 
At times, there will be a situation in which we need to execute a block of code several times. Usually, we write the instructions in a sequence. But programming allows us to repeat the execution with the same set of code again and again to achieve the desired result. This concept is known as looping and the programming construct which allows the repetition is known as the loop.
 

Types of loops in R

 
There are various types of looping constructs available in R,
  1. for loop
  2. while loop
  3. repeat loop
Let us understand each type of loop in detail.
 

For Loop

 
A for loop is a looping construct which allows repeating a particular block of code for a specified number of times.
  1. for(i in 1:5){  
  2. print(i)  
  3. }  
The above code snippet prints the numbers 1 to 5. I just took this simple example to make you familiar with for loop.
 
In line 1, the for loop is mentioned. In the brackets next to it, "i in 1:5" means variable i will take values from 1 to 5 one by one. In the first iteration, the value of "i" will be 1, in the second iteration 2 and so on.
 

While Loop 

 
A while loop keeps on executing the same block of code until the condition is true. As soon as the condition turns false, the loop stops.
  1. i<-1  
  2. while(i<=5){  
  3.   print(i)  
  4.   i<-i+1  
  5. }  
The above loops also print 1 to 5. The for loop is used when the number of iterations is known and while loop is used when the number of iterations is not known.
 

Repeat Loop

 
The repeat loop is used to iterate over a block of code but it does not have a conditional check to exit from the loop. In this loop, we need to explicitly stop the loop by specifying the break statement. If we do not write a break statement in the repeat loop, the loop will run for infinite times.
  1. x <- 1  
  2. repeat {  
  3.   print(x)  
  4.   x <- x+1  
  5.   if (x == 6){  
  6.     break  
  7.   }  
  8. }  
In the code above, we start printing the value of x and increment it. The if condition checks if the value of x is 6. If the value is not 6, the repeat block is executed again. When the loop runs for the 5th time, the value of x (i.e 5) is printed and then it is incremented to 6. The if condition is satisfied and break statement is executed. This causes the loop to stop.
 
These are the 3 types of loops in R. Now that we know the various types of loops in R, let us go through a few examples.
 

Examples of loops in R

 
Finding out even numbers in a given range
  1. for(i in 1:10){  
  2.   if(i%%2==0){  
  3.     print(i)  
  4.   }  
  5. }  
In the above code, the for loop runs 10 times. In the first run, the value of i is 1. The value of "i" is then checked using the if statement. "%%" is used to find the remainder. i%%2 means divide the value of i with 2. If the remainder of i%%2 is zero, this means that "i" is fully divisible by number two and hence it is an even number. If we find that i is even, we are printing it in line number 3.
 
Post this, the value of i is incremented by 1 and the loop iterates till the value of i becomes 10. 
 
Try changing the range and observe the output. 
 
Finding out whether a number is prime or not
  1. num = 13  
  2. count = 0  
  3.   for(i in 1:num) {  
  4.     if ((num %% i) == 0) {  
  5.       count<-count+1  
  6.     }  
  7.   }  
  8. if(count == 2) {  
  9.   print("Prime number")  
  10. else {  
  11.   print("Not a prime number")  
  12. }  
A prime number is a number which is divisible ONLY by 1 and itself. This means if we start dividing a number by 1, it must be divisible only 2 times - Once when it is divided by 1 and other time when it is divided by itself. The same logic is used in above code snippet. 
 
In line 1, variable num is assigned value 13. (You can try assigning various values and see the result)
 
In line 2, the variable count is assigned value 0. This variable is used to check how many times the number is divisible.
 
From line 3 till line 7, we have the for loop which iterates till the number itself. In this case, we have the num as 13. So, the loop will run from 1 till 13. Suppose, you change the value of num to 4, then the loop will run from 1 till 4.
 
Every time the loop runs, we divide num with i. In the first iteration, the num will be divisible by i as the value of i is 1. The count will be increased. In the second iteration, the num will be divided by 2. As, in this case the num is 13, it is not divisible by 2 and hence the count will not be increased.
 
Similarly, the loop will run until i becomes 13. When I would be 13, it would divide num and count will be increased.
 
In line 8, we check whether the count is 2. If the count is 2, the message "Prime number" is displayed. Else, the message "Not a prime number" is displayed.
 
I hope with this example, you will have understood how a loop works and the application of if-else statement too. 
 
Printing table of a number
  1. i<-1    
  2. num<-5  
  3. while(i<=12){  
  4.   print(i*num)    
  5.   i<-i+1    
  6. }    
Try running the code by changing the value of num. You can also try printing the table of a number using a for or repeat loop. In the code snippet above, the variable i is used to iterate from 1 till 12. The number for which the table will be printed is stored in the num variable.
 
I hope this article on loops in R helped you in understanding the various loops and a few simple examples.


Similar Articles