if, else and ifelse()
Two questions arrive from the garden committee. "Was this a big week overall?" needs one answer. "Which plots were heavy?" needs an answer for every plot. R has a different tool for each, and mixing them up is one of the most common beginner errors.
The rule
ifasks one question;ifelse()asks every element.
if and else run one block of code or another, based on a single TRUE or FALSE.
kg <- c(12.5, 8, 15, 3.5, 6)
total <- sum(kg) # 45
if (total > 40) {
cat("Big week: share the surplus\n")
} else if (total > 20) {
cat("Normal week\n")
} else {
cat("Quiet week\n")
}R checks the conditions from the top and runs the first block whose condition is TRUE, so this prints "Big week". Three rules:
- The condition must be exactly one TRUE or FALSE. Since R 4.2, a longer condition such as
if (kg > 7)is an error: the condition has length > 1. - An
NAcondition is also an error: missing value where TRUE/FALSE needed. - Keep
} else {on one line. At the top level, R treats a line that ends with}as a finished statement, so anelseon the next line is a syntax error.
if also returns a value, so it can sit on the right of an assignment:
size <- if (total > 40) "big" else "small" # "big"ifelse(test, yes, no) makes the choice for every element of a vector at once:
ifelse(kg > 7, "heavy", "light")
# "heavy" "heavy" "heavy" "light" "light"For many fixed options keyed on a single value, switch() is tidier than a chain of else if: switch("bean", tomato = "red", bean = "green", "other") returns "green".
The shortcut
Before you write anything, count the answers you need. One answer for the whole situation: if. One answer per element: ifelse(). If you want if but have a vector, shrink it to one value first with sum(), any() or all().
Test every element
kg > 7gives TRUE TRUE TRUE FALSE FALSE.
You can nest ifelse() for three bands: the inner call handles whatever the outer test sends to its no side.
Drills
Answer fast — trust the rule.
What happens with if (kg > 7) print("heavy") in R 4.2 or later?
With watered <- c(TRUE, FALSE, TRUE, TRUE, FALSE), what is ifelse(watered, "yes", "no")?
What does x <- NA; if (x > 1) "big" else "small" do?
What is size after size <- if (sum(kg) > 40) "big" else "small"?
Which label does plot E (6 kg) get from ifelse(kg > 10, "high", ifelse(kg > 5, "mid", "low"))?
Remember
ifasks one question;ifelse()asks every element.- Shortcut: count the answers you need. One means
if; one per element meansifelse(). - Trap: vector or NA conditions inside
if, andelsestarting a new line.
