Conditionals
R's if/else if/else reads close to other C-family languages, with one catch worth knowing up front: the condition has to be a single TRUE or FALSE, never a vector.
if / else if / else
R conditional.R
temp <- 15
if (temp > 25) {
print("Hot")
} else if (temp > 10) {
print("Mild")
} else {
print("Cold")
}
Console
[1] "Mild"
R checks each condition top to bottom and runs the first block whose condition is TRUE, skipping the rest — temp > 25 fails, temp > 10 succeeds, so "Mild" prints and the else block never runs.
A shorthand for simple cases: ifelse()
For a quick, vectorized either/or, ifelse() checks a whole vector at once and returns a matching vector of results — no if/else blocks needed:
R ifelse.R
scores <- c(88, 45, 72, 91) ifelse(scores >= 60, "Pass", "Fail")
Console
[1] "Pass" "Fail" "Pass" "Pass"
Note: A regular
if() expects exactly one logical value, not a vector. Handing it a vector like scores >= 60 directly is an error in current R (older versions just used the first element with a warning) — that's exactly the situation ifelse() above is built for.