Skip to main content

Loops in R

Loops in R are control structures that allow you to execute a piece of code repeatedly until a certain condition is met. They are fundamental in programming and extremely useful when it comes to automating repetitive tasks.

In this tutorial, we will cover three types of loops in R:

  • for loop
  • while loop
  • repeat loop

Let's begin!

For Loop

A 'for' loop in R is used to iterate over a sequence. Here's the basic syntax:

for (value in sequence) {
# Code to execute
}

For example, if we want to print the numbers 1 to 5, we can do it like this:

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

In this example, i takes on each value in the sequence 1:5 one by one, and for each value, it executes the code within the braces (i.e., it prints the value of i).

While Loop

A 'while' loop in R is used to repeat a block of code as long as a certain condition is true. Here's the basic syntax:

while (condition) {
# Code to execute
}

Let's say we want to print numbers starting from 1 and continue until the number is less than or equal to 5. We can do it like this:

i <- 1
while (i <= 5) {
print(i)
i <- i + 1
}

Here, the loop will keep executing as long as i is less than or equal to 5. Inside the loop, we increment i by 1 in each iteration.

Repeat Loop

A 'repeat' loop in R is used to execute a block of code indefinitely until a break condition is met. Here's the basic syntax:

repeat {
# Code to execute
if (condition) {
break
}
}

For example, if we want to print numbers from 1 to 5, we can do it like this:

i <- 1
repeat {
print(i)
i <- i + 1
if (i > 5) {
break
}
}

In this example, the loop will keep executing indefinitely. However, we have a break condition inside the loop which breaks the loop when i becomes larger than 5.

Loop Control Statements

There are two loop control statements in R:

  1. break: It is used to exit the loop prematurely. It stops the execution of the loop and transfers the control to the next statement following the loop.

  2. next: It is used to skip the current iteration of the loop and continue with the next iteration.

Use them wisely to control the flow of your loops.

Conclusion

Loops in R are powerful tools that allow you to automate repetitive tasks effectively. In this article, we discussed the three types of loops in R: 'for', 'while', and 'repeat'. We also looked at how to control the flow of loops with 'break' and 'next' statements.

Remember, practice is key to master loops in R. So, try to solve different problems with loops and experiment with different scenarios. Happy coding!