R If Else
The if / else construct lets an R program branch and run different code depending on whether a condition is TRUE or FALSE.
Basic if Statement
An if statement checks a single condition in parentheses; if that condition is TRUE, the code inside the curly braces runs, and if it's FALSE, R simply skips over it and continues with whatever comes next.
A Simple if
temperature <- 38
if (temperature > 37) {
print("Fever detected")
}Adding an else Branch
Pair if with else to provide an alternative block of code that runs only when the condition is FALSE. Together they guarantee that exactly one of the two branches executes.
if / else
temperature <- 36.5
if (temperature > 37) {
print("Fever detected")
} else {
print("Temperature normal")
}Chaining Conditions with else if
To test several conditions in sequence, chain else if blocks between the first if and the final else. R checks each condition top to bottom and runs the first block whose condition is TRUE, ignoring the rest — so order the conditions from most specific to least specific.
Grading Scale
score <- 82
if (score >= 90) {
grade <- "A"
} else if (score >= 75) {
grade <- "B"
} else if (score >= 60) {
grade <- "C"
} else {
grade <- "F"
}
print(grade)ifelse() — the Vectorized Version
Exercise: R If Else
In an R script run non-interactively, where must else appear relative to the if block above it?