For Loop and While Loop in R

In this article we discuss the basics of loop in R. You can use loops to repeatedly execute a block of code efficiently. In simpler terms, if we want to repeat a set of operations repeatedly, we use loops in R.

There are two types of loops in R; for loops and while loops. These loops are used to iterate over sequences, perform calculations, and automate repetitive tasks.

For Loop in R

A “for loop” is used when we know the number of times we want to execute a block of code or we can extract the length using some function. It is typically used for iterating over a sequence which could be either vectors, matrices or numbers.

Download Example File

The basic syntax of a for loop will be as follows

for (variable in sequence) {
code to be executed 
}

For instance, we are going to print number 1 to 10 using following command.

for(i in 1:10){
      print(i)
}

This command will instruct R to repeat a set of commands for each value of i in the sequence from 1 to 10. In other words, i will take on the values 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10, one at a time. you can assign any name to i so instead of i you can use a more descriptive name. The executed command will generate the following results

for loop in R

Similarly, a range of numbers can be saved in a vector and use that vector within the loop.

range <- 14:22

for(number in range){
          print(number) 
}

The above command will generate range of integers from 14 to 22 in the variable named range.

We can also create a sequence of numbers and add increments to those numbers by our own choice. For instance, if we want to create numbers from 1 to 30 in a way that numbers followed by 1 are incrementing by 3, we use the following command

for(i in seq(from=1, to=30, by=3)) {
     print(i) 
}

In the above command we have used a seq function that will generate a range from 1 to 30 and these numbers will be incremented by 3. The above command will generate following sequence, creating integers that increase by 3.

for loop with incremental iteration

Break or Skip a Loop

We can interrupt a loop using the break function. For example, we want for loop to print numbers from 1 to 10, however, we also to include an if statement with a break statement to stop the loop when i is greater than 6. For this purpose, we use the following command

for(i in 1:10) {
  if(i > 6) {
    break 
}
    print(i) 
}

So, after the command is executed, it will print the numbers from 1 to 6, and then the loop will stop because of the break statement when i becomes greater than 6.

break loop in R

We can also create a break of an iteration in loop using for loop in R. For instance, if we want to print the values as long as they are equal to 1, we can do this using for loop. When a value other than 1 is encountered, the loop is terminated using the break statement. The code for this process will be following

sample <- c(1,1,1,1,0,1,1,1)
for(i in sample) {
     if(i!=1 ) {
       break
}
       print(i)
}

The integer 1 is generated 4 times because after that a break is incurred due to the presence of a non-one or zero number.

Instead of creating a break, the iteration can be skipped by using the for loop. Like in previous command, we instructed R to take a break when any other number than 1 appears, we can also instruct it to continue the iteration and skip the number other than one. The command for this process will be following

sample <- c(1,1,1,1,0,1,1,1)
for(i in sample) {
     if(i!=1 ) {
       next
}
       print(i) 
}

After executing the above command, the iteration will continue for number one, skipping the zero number.

skip loop in r

While loop in R

A while loop is used when you want to repeatedly execute a block of code as long as a certain condition is met. It is useful when you don’t know in advance how many times the loop should be executed.

The basic syntax of while loop is following

while (condition) {
          Code to be executed 
}

The most common error when working with while loop is not to increment the condition within the loop. For instance, the following command will enter an infinite loop.

num <- 1
while(num < 10) {
         print(num) 
}

The above command initializes a variable called num with the value 1. It sets the variable to 1 as the starting point for the loop, and does not increament it hence the condition num < 10 is always true and the loop continues infinitely.

To avoid an infinite loop, we can increment num inside the loop by using the following command.

while(num < 10) {
         print(num)
         num <- num+1 
}

The command initializes a variable num to 1 and then enters a loop that repeatedly prints the value of num and increments it by 1 in each iteration. The loop will continue executing until num reaches 10.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Tweet
Share
Share
Pin