Decisions and loops
if and else
temperature <- 31
if (temperature > 30) {
message <- "Hot"
} else if (temperature > 20) {
message <- "Warm"
} else {
message <- "Cool"
}
if works on one value. In R, if is also an expression, so label <- if (x > 0) "positive" else "not positive" works.
ifelse: decisions for whole vectors
For a vector, if is the wrong tool. ifelse checks every element:
rain <- c(0, 12, 3, 30)
ifelse(rain > 10, "wet", "dry") # "dry" "wet" "dry" "wet"
for loops
for (city in c("Harare", "Mutare")) {
cat("Hello from", city, "\n")
}
for (i in 1:3) {
cat("Round", i, "\n")
}
R has loops, but idiomatic R prefers vectorised code (x * 2, ifelse, sum), which is shorter and much faster on large data. Loops are still right when each step depends on the previous one, like a running total. When you do loop, create the result first (numeric(n) makes a vector of n zeros) and fill it in, rather than growing it.
Your task
grade(mark):"A"for 80+,"B"for 60+,"C"for 50+, else"F".pass_fail(marks):"pass"or"fail"for each mark (pass is 50+), usingifelse.running_total(x): a vector where each element is the sum so far, written with aforloop.