When you need to do something over and over, loops are your friend. R gives you for loops and while loops. But R also has a secret weapon โ vectorized operations that often let you skip loops entirely. Let's look at all three approaches.
for Loops
A for loop repeats code for each element in a vector or list. You give it a temporary variable that takes on each value one by one.
fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
print(paste("I like", fruit))
}
# Loop over a sequence of numbers
for (i in 1:5) {
print(i * 2)
}
Try it Yourself โ
while Loops
A while loop keeps going as long as a condition is true. Be careful โ if the condition never becomes false, you'll get an infinite loop!
count <- 1
while (count <= 5) {
print(paste("Count is", count))
count <- count + 1
}
Try it Yourself โ
Avoiding Loops with Vectorization
R is built for vectorized operations โ they're faster and cleaner than loops. Instead of looping through each element, you can operate on the whole vector at once. This is the R way.
numbers <- 1:10
# Loop approach
squared_loop <- numeric(10)
for (i in 1:10) {
squared_loop[i] <- numbers[i] ^ 2
}
# Vectorized approach โ much simpler!
squared_vec <- numbers ^ 2
print(squared_vec)
Try it Yourself โ