AnyCompiler

Control Flow

if/else in R works the way you'd expect from any C-family or scripting language — a condition, a block to run when it's TRUE, an optional block for when it's FALSE.

age <- 20
if (age >= 18) {
  print("adult")
} else {
  print("minor")
}
Output
[1] "adult"

for loops — the exception, not the rule

for (item in sequence) and while (condition) both exist in R and work as expected — but after everything the last two lessons covered, writing a for loop specifically to walk over a vector's elements and accumulate a result is usually a sign you're fighting R's design rather than using it. Nearly every lesson so far has shown the same operation done without a loop at all.

total <- 0
for (i in 1:5) {
  total <- total + i
}
print(total)
print(sum(1:5))
Output
[1] 15
[1] 15

Both lines print 15 — the for loop and sum(1:5) compute the exact same answer, but sum() does it in one call, on the whole vector 1:5 at once, with no manual accumulator and no loop variable to manage. for loops in R are for genuinely sequential tasks (reading files one at a time, printing a running log) — not for the kind of per-element math vectorized operations already handle. Next: functions — function(), default arguments, and implicit return values.

Practice exercise

Given score <- 72, use if/else to print "pass" if score is at least 60, otherwise print "fail".