Loops in R
Loops are used to repeat a block of code multiple times based on conditions or iterations. In R, there are three main types of loops: for, while, and repeat. Each serves different purposes and is used in different scenarios.
for Loop
The for loop iterates over a sequence of values, executing the block of code for each value.
Syntax:
for (variable in sequence) { # Code to execute for each value in the sequence }
Example:
# Print numbers from 1 to 5 for (i in 1:5) { print(i) }
Example with Vectors:
# Sum elements of a vector numbers <- c(1, 2, 3, 4, 5) sum <- 0 for (num in numbers) { sum <- sum + num } print(sum) # Prints 15
Example with Lists:
# Print each element of a list my_list <- list(a = 1, b = 2, c = 3) for (item in my_list) { print(item) }
while Loop
The while loop continues to execute a block of code as long as a specified condition remains true.
Syntax:
while (condition) { # Code to execute while condition is true }
Example:
# Print numbers from 1 to 5 count <- 1 while (count <= 5) { print(count) count <- count + 1 }
Example with Accumulation:
# Calculate the sum of numbers from 1 to 5 sum <- 0 num <- 1 while (num <= 5) { sum <- sum + num num <- num + 1 } print(sum) # Prints 15
repeat Loop
The repeat loop is similar to the while loop but does not have a built-in condition for stopping. It requires an explicit break statement to exit the loop.
Syntax:
repeat { # Code to execute if (condition) { break } }
Example:
# Print numbers from 1 to 5 count <- 1 repeat { print(count) count <- count + 1 if (count > 5) break }
Example with Condition Check:
# Find the first number greater than 10 num <- 1 repeat { if (num > 10) break num <- num + 1 } print(num) # Prints 11
Using break and next in Loops
- break: Immediately exits the current loop.
- next: Skips the current iteration and proceeds to the next iteration of the loop.
Example of break:
# Find the first even number greater than 10 for (num in 11:20) { if (num %% 2 == 0) { print(num) break } }
Example of next:
# Print only odd numbers from 1 to 10 for (num in 1:10) { if (num %% 2 == 0) next print(num) }
Nested Loops
Loops can be nested within each other to perform more complex operations.
Example:
# Print a multiplication table from 1 to 3 for (i in 1:3) { for (j in 1:3) { print(paste(i, "*", j, "=", i * j)) } }
Vectorized Operations
In R, many operations can be vectorized, meaning they can be performed on entire vectors without explicit loops, which can be more efficient.
Example:
# Adding two vectors without a loop vec1 <- c(1, 2, 3, 4, 5) vec2 <- c(10, 20, 30, 40, 50) result <- vec1 + vec2 print(result) # Prints 11 22 33 44 55
Applying Functions to Vectors and Data Frames
Functions like lapply, sapply, apply, and mapply can be used to apply operations over vectors, lists, or data frames in a loop-like manner.
Example with lapply:
# Applying a function to each element of a list my_list <- list(a = 1, b = 2, c = 3) squared_list <- lapply(my_list, function(x) x^2) print(squared_list)
Example with apply:
# Applying a function to each row of a matrix mat <- matrix(1:6, nrow = 2) row_sums <- apply(mat, 1, sum) # Sum of each row print(row_sums)
Performance Considerations
While loops are essential for certain tasks, vectorized operations and apply functions are often more efficient in R. They avoid the overhead of explicit loops and take advantage of optimized C code.