Week 6: Automating Repetitive Tasks with Loops

Learn how to use `for` and `while` loops in R to execute code repeatedly.

Explore Chapter 6

Chapter 6: Repeating Actions with Loops

`for` Loops: Iterating Over Sequences.

Loops are essential for automating repetitive tasks. A `for` loop in R iterates over each element in a sequence (like a vector or list), executing a block of code for each element.

Syntax

for (variable in sequence) {
  # Code block to execute for each element in 'sequence'
  # 'variable' takes the value of the current element
  statement1
  statement2
  # ...
}
  • The `for` keyword starts the loop.
  • `variable` is a temporary variable that holds the current element from the `sequence` during each iteration.
  • `in` separates the variable from the sequence being iterated over.
  • `sequence` is typically a vector or list (or other iterable object).
  • The code block to be executed is enclosed in curly braces `{}`.

Iterating Over a Vector

fruits <- c("apple", "banana", "cherry")

for (fruit in fruits) {
  print(paste("Current fruit:", fruit))
}
# Output:
# [1] "Current fruit: apple"
# [1] "Current fruit: banana"
# [1] "Current fruit: cherry"

Iterating Over a Sequence of Numbers

Often, you'll want to loop a specific number of times or over indices. The colon operator `:` is useful for creating integer sequences.

# Loop 5 times (i will be 1, 2, 3, 4, 5)
for (i in 1:5) {
  print(paste("Iteration number:", i))
}

# Iterating through indices of a vector
my_vector <- c(10, 20, 30)
for (i in 1:length(my_vector)) {
  print(paste("Element at index", i, "is", my_vector[i]))
}

`while` Loops: Repeating Based on a Condition.

A `while` loop repeatedly executes a block of code as long as a specified logical condition remains `TRUE`.

Syntax

while (condition) {
  # Code block to execute as long as 'condition' is TRUE
  statement1
  statement2
  # ...
  # IMPORTANT: Something inside the loop must eventually make 'condition' FALSE!
}
  • The `while` keyword is followed by the condition in parentheses `()`.
  • The condition must evaluate to a single `TRUE` or `FALSE`.
  • The code block in braces `{}` executes repeatedly.
  • Crucially, the code within the loop must modify variables involved in the condition so that it eventually becomes `FALSE`. Otherwise, the loop will run forever (an infinite loop).

Example: Counter

count <- 1

while (count <= 5) {
  print(paste("Count is:", count))
  count <- count + 1 # Increment count to eventually stop the loop
}
# Output:
# [1] "Count is: 1"
# [1] "Count is: 2"
# [1] "Count is: 3"
# [1] "Count is: 4"
# [1] "Count is: 5"

Example: Waiting for a condition

value <- 0
while (value < 0.9) {
  value <- runif(1) # Generate a random number between 0 and 1
  print(paste("Current random value:", value))
}
print("Found a value >= 0.9!")

`break` and `next` Statements: Controlling Loop Execution.

You can alter the standard flow of loops using the `break` and `next` statements.

`break` Statement

The `break` statement immediately terminates the innermost loop (`for` or `while`) it is contained within. Execution continues with the first statement after the terminated loop.

for (i in 1:10) {
  print(i)
  if (i == 5) {
    print("Found 5, stopping loop.")
    break # Exit the loop
  }
}
# Output: 1 2 3 4 5 "Found 5, stopping loop."

`next` Statement

The `next` statement skips the rest of the current iteration of a loop and immediately proceeds to the next iteration. It's similar to `continue` in other languages like Python.

for (i in 1:7) {
  if (i %% 2 == 0) { # Check if i is even
    print(paste("Skipping even number:", i))
    next # Go to the next iteration
  }
  print(paste("Processing odd number:", i))
}
# Output:
# [1] "Processing odd number: 1"
# [1] "Skipping even number: 2"
# [1] "Processing odd number: 3"
# [1] "Skipping even number: 4"
# [1] "Processing odd number: 5"
# [1] "Skipping even number: 6"
# [1] "Processing odd number: 7"

Nested Loops: Loops Inside Loops.

You can place one loop inside another loop. This is useful for tasks like iterating over elements in a matrix or other multi-dimensional structures.

Example: Iterating through a Matrix

my_matrix <- matrix(1:6, nrow = 2, ncol = 3)
print(my_matrix)

# Loop through rows
for (row_num in 1:nrow(my_matrix)) {
  # Loop through columns for the current row
  for (col_num in 1:ncol(my_matrix)) {
    element <- my_matrix[row_num, col_num]
    print(paste("Element at row", row_num, "col", col_num, "is:", element))
  }
}

The inner loop completes all its iterations for each single iteration of the outer loop. Be mindful that nested loops can become computationally intensive if the sequences are very large.

Syllabus