if, else and ifelse()
if and else choose between blocks of code using a single TRUE or FALSE, while ifelse() makes the same kind of choice separately for every element of a vector.
Distinguish one control-flow decision from element-by-element selection.
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".