Skip to main content

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

  1. The computer checks: temperature > 10

  2. 5 > 10 is FALSE

  3. So the else part runs.

  4. 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:

  1. i = 1 → print 1

  2. i = 2 → print 2

  3. i = 3 → print 3

  4. i = 4 → print 4

  5. i = 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.