Loops in R

📘 Introduction

Loops are control structures that allow a block of code to be executed repeatedly until a specified condition is met. Instead of writing the same code multiple times, loops automate repetitive tasks, making programs shorter, more efficient, and easier to maintain.

Information

R provides several looping constructs, including for, while, and repeat. Each loop is suited for different programming scenarios.

đŸŽ¯ Why Use Loops?

  • Reduce repetitive code.
  • Automate repeated tasks.
  • Process collections such as vectors and lists.
  • Perform calculations efficiently.
  • Improve program readability and maintainability.

📚 Types of Loops in R

Loops
for Loop
while Loop
repeat Loop

🔹 The for Loop

The for loop executes a block of code for every element in a sequence, vector, list, or other iterable object.

Syntax of for Loop

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

Example: Printing Numbers

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

Output

Console Output

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

🔸 The while Loop

The while loop repeatedly executes a block of code as long as the specified condition remains TRUE.

Syntax of while Loop

while (condition) {
  # Code to execute
}

Example: while Loop

count <- 1

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

Output

Console Output

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

🔁 The repeat Loop

The repeat loop executes indefinitely until it is explicitly terminated using the break statement.

Syntax of repeat Loop

repeat {
  # Code to execute

  if (condition) {
    break
  }
}

Example: repeat Loop

count <- 1

repeat {
  print(count)

  count <- count + 1

  if (count > 5) {
    break
  }
}

Output

Console Output

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

⏚ The break Statement

The break statement immediately terminates the current loop, regardless of the loop condition.

Example: break

for (i in 1:10) {

  if (i == 6) {
    break
  }

  print(i)
}

Output

Console Output

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

⏭ The next Statement

The next statement skips the current iteration and continues with the next iteration of the loop.

Example: next

for (i in 1:5) {

  if (i == 3) {
    next
  }

  print(i)
}

Output

Console Output

[1] 1
[1] 2
[1] 4
[1] 5

🔁 Looping Through a Vector

A for loop is commonly used to process each element of a vector.

Loop Through a Vector

fruits <- c("Apple", "Banana", "Orange")

for (fruit in fruits) {
  print(fruit)
}

Output

Console Output

[1] "Apple"
[1] "Banana"
[1] "Orange"

🔄 Nested Loops

A loop placed inside another loop is called a nested loop. Nested loops are useful for working with tables, matrices, and multidimensional data.

Nested for Loop

for (i in 1:3) {

  for (j in 1:2) {
    print(paste("Row:", i, "Column:", j))
  }

}

🧮 Real-World Example

The following program calculates the total sales for five days.

Calculating Total Sales

sales <- c(1200, 1500, 1800, 1700, 1600)

total <- 0

for (amount in sales) {
  total <- total + amount
}

print(total)

Output

Console Output

[1] 7800

📊 Loop Execution Flow

Start Loop
Check Condition
Condition is TRUE
Condition is FALSE
Execute Loop Body
Update Loop Variable
Repeat
Exit Loop

📋 Comparison of Loops

LoopPurposeBest Used When
forIterates over a sequence.The number of iterations is known.
whileRepeats while a condition is true.The number of iterations is unknown.
repeatCreates an infinite loop until stopped.The loop should continue until a manual exit condition is reached.

âš ī¸ Infinite Loops

An infinite loop occurs when the loop condition never becomes FALSE. This causes the program to run indefinitely.

Avoid Infinite Loops

count <- 1

while (count <= 5) {

  print(count)

  count <- count + 1

}

Warning

Always ensure that the loop condition eventually becomes FALSE, or use a break statement to terminate the loop.

âš ī¸ Common Mistakes

MistakeExplanationSolution
Forgetting to update the loop variableMay create an infinite loop.Update the loop variable during each iteration.
Using the wrong loop typeMay result in unnecessary complexity.Choose the loop that best matches the problem.
Misplacing break or nextCan change loop behavior unexpectedly.Place them carefully inside conditional statements.
Modifying the loop sequence incorrectlyCan produce unexpected results.Avoid changing the sequence while iterating.

💡 Best Practices

  • Use for loops when the number of iterations is known.
  • Use while loops when repetition depends on a condition.
  • Use repeat only when an explicit exit condition is required.
  • Keep loop bodies simple and readable.
  • Whenever possible, use R's vectorized functions instead of loops for better performance.

Best Practice

Although loops are essential, R is optimized for vectorized operations. Use loops when necessary, but prefer vectorized functions such as apply(), lapply(), or arithmetic on vectors for improved efficiency.

📝 Summary

Loops enable R programs to perform repetitive tasks efficiently. You learned about the for, while, and repeat loops, along with the break and next statements for controlling loop execution. You also explored nested loops, vector iteration, loop execution flow, and best practices for writing efficient looping code. Mastering loops is an important step toward solving real-world programming problems and processing large amounts of data.

>>"Loops automate repetition, allowing programs to solve complex tasks with simple and efficient code."