Conditionals: if and else
Prerequisites: Logical values and comparisons
A conditional runs code only when a condition is true.
Real-world analogy: "If it's raining, take an umbrella; otherwise, wear sunglasses."
Syntax
if (condition) {
# runs when condition is TRUE
} else if (other_condition) {
# runs when the first was FALSE and this one is TRUE
} else {
# runs otherwise
}
Example
temperature <- 18
if (temperature > 25) {
cat("It's hot\n")
} else if (temperature > 15) {
cat("It's pleasant\n")
} else {
cat("It's cold\n")
}
Expected output
It's pleasant
if returns a value
age <- 20
status <- if (age >= 18) "adult" else "minor"
status
[1] "adult"
if is not vectorized — use ifelse for vectors
if needs a single TRUE or FALSE. To choose a value for every
element of a vector, use ifelse():
ages <- c(12, 25, 37, 8)
ifelse(ages >= 18, "adult", "minor")
[1] "minor" "adult" "adult" "minor"
Passing a whole vector to if is an error:
ages <- c(12, 25)
if (ages >= 18) cat("adult\n")
Error in if (ages >= 18) cat("adult\n") : the condition has length > 1
Common mistakes
- Using
&or|in anifcondition with vectors. Use&&and||, which require single values. - An
ifcondition that'sNA— for example, comparing a missing value — givesmissing value where TRUE/FALSE needed. Checkis.na()first.
Practice
Given scores <- c(45, 72, 90), use ifelse to label each score
"pass" (50 or more) or "fail".
Show solution
scores <- c(45, 72, 90)
ifelse(scores >= 50, "pass", "fail")
[1] "fail" "pass" "pass"