Control Flow
The Pipe %>% (The Assembly Line)
The symbol %>% means “and then…”.
Both of these lines are identical, which would you prefer to read? (Note |> is another way to write %>%)
print(round(sqrt(10), 2))
10 |> sqrt() |> round(2) |> print()
For a real world example of how one may use the pipe
library(dplyr)
mtcars %>%
filter(wt > 3) %>% # 1. Filter for cars heavier than 3,000 lbs
group_by(cyl) %>% # 2. Group by number of cylinders
summarize(avg_mpg = mean(mpg)) # 3. Calculate the average MPG
If / Else (The Fork in the Road)
An if/else statement lets the computer make a decision.
The program checks a condition:
If it is TRUE, it runs one block of code.
If it is FALSE, it runs another.
temperature <- 5
if (temperature > 10) {
print("You can wear a t-shirt")
} else {
print("Wear a jacket")
}
What happens
The computer checks:
temperature > 105 > 10is FALSESo the else part runs.
Output:
"Wear a jacket"
Think of it like a fork in the road:
One path if the condition is true
Another path if it’s false.
Loops (The Treadmill)
A loop repeats code multiple times.
Instead of writing the same instruction again and again, you let the computer do it.
Example
for (i in 1:5) {
print(i)
}
What happens
The computer runs the code 5 times.
Steps:
i = 1→ print 1i = 2→ print 2i = 3→ print 3i = 4→ print 4i = 5→ print 5
Output:
1 2 3 4 5
Audit Check (Important)
When using loops, ask:
1. Does the loop end?
Bad example (infinite loop):
while (TRUE) { print("This never stops") }
2. Could this be simpler?
Sometimes R has built-in functions that replace loops.
Instead of:
total <- 0 for (i in 1:5) { total <- total + i }
You can write:
sum(1:5)
This is shorter, safer, and faster.