Lesson 5 of 8 · 9 min

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

  1. grade(mark): "A" for 80+, "B" for 60+, "C" for 50+, else "F".
  2. pass_fail(marks): "pass" or "fail" for each mark (pass is 50+), using ifelse.
  3. running_total(x): a vector where each element is the sum so far, written with a for loop.
script.R
grade <- function(mark) {
}

pass_fail <- function(marks) {
}

running_total <- function(x) {
}

print(running_total(c(5, 10, 3)))

R 4.5 runs right here in your browser. The first run downloads about 25 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…