Iteration Constructs: Loops
Why Learn Loops in Data Analytics?
Imagine you are monitoring website traffic logs. You have a vector of hourly visitor counts: c(120, 95, 150, 80, 200, 110). You want to:
- Scan each hourly count.
- If the count is below
100, print an alert message. - Keep a running tally of how many hours had low traffic.
To look at each hour one-by-one and make decisions, you need Loops. Loops allow you to repeat a block of code for every item in a dataset, automating repetitive inspection tasks.
1. The for Loop
The for loop is used to iterate over a sequence (like a vector or a list) a pre-determined number of times.
Syntax
for (variable in sequence) {
# code to repeat
}
Example: Iterating over a Vector
visitor_counts <- c(120, 95, 150, 80, 200)
for (count in visitor_counts) {
if (count < 100) {
print(paste("Alert: Low traffic hour with only", count, "visitors!"))
}
}
2. The while Loop
The while loop repeats a block of code as long as a specified condition remains TRUE.
attempts <- 1
while (attempts <= 3) {
print(paste("Attempt number:", attempts))
attempts <- attempts + 1 # Increment to avoid infinite loop
}
When using while() loops to simulate random walks or other statistical behaviors where the termination condition relies on chance, always enforce a maximum iteration limit. This prevents your code from running infinitely if the condition is never met:
max_iterations <- 1000
step <- 1
current_value <- 0
# Run until threshold is exceeded OR limit is hit
while (abs(current_value) < 10 && step <= max_iterations) {
current_value <- current_value + rnorm(1)
step <- step + 1
}
3. The repeat Loop (Unique to R)
R features a third loop type called repeat. It has no condition check at the start; it simply repeats a block of code indefinitely until it encounters a break statement inside.
counter <- 1
repeat {
print(counter)
counter <- counter + 1
if (counter > 3) {
break # Exit the loop
}
}
4. break vs. next
To control loop execution dynamically, R provides two keywords:
break: Exits the entire loop immediately.next: Skips the rest of the current iteration and jumps directly to the start of the next iteration (equivalent to Python'scontinuekeyword!).
numbers <- 1:5
for (num in numbers) {
if (num == 3) {
next # Skip printing 3
}
print(num) # Outputs: 1, 2, 4, 5
}
Hands-on Exercises
Exercise 1: Finding High-Temperature Alerts
You have a vector of temperature readings: c(32, 35, 41, 38, 43, 30).
Write R code to:
- Loop through the vector using a
forloop. - If a temperature is greater than
40, print the temperature and stop the loop immediately using abreakstatement. - If the temperature is 40 or below, print
"Normal".
# Write your code below and click Run Code
Click to view Answer
temps <- c(32, 35, 41, 38, 43, 30)
for (temp in temps) {
if (temp > 40) {
print(paste("Critical Heatwave Alert:", temp))
break
}
print("Normal")
}
# Output should show "Normal", "Normal", then the Alert, then stop.
Exercise 2: Even Number Tally
You want to count the number of even integers in a sequence from 1 to 15 using a loop.
Write R code to:
- Create a variable
even_count <- 0. - Write a
forloop that iterates through1:15. - If a number is odd, skip to the next iteration using
next. - If it is even, increment
even_countby1. - Print the final
even_countvalue after the loop exits.
# Write your code below and click Run Code
Click to view Answer
even_count <- 0
for (num in 1:15) {
if (num %% 2 != 0) {
next # Skip odd numbers
}
even_count <- even_count + 1
}
print(paste("Total even numbers:", even_count)) # Output: 7