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)
Note: When running R code from a script (not typed line by line at the console), else must start on the same line as the closing brace of the if block. Putting else on its own new line makes R think the if statement already finished, and it will throw an error when it then sees a stray else.

ifelse() — the Vectorized Version

Use Caseif / elseifelse()
InputA single TRUE/FALSE valueA vector of any length
OutputRuns one block of codeReturns a vector of results, one per element
Typical useControlling which code path runsRecoding or transforming a whole column at once
Exampleif (x > 0) "pos" else "neg"ifelse(x > 0, "pos", "neg")

Exercise: R If Else

In an R script run non-interactively, where must else appear relative to the if block above it?