Learn R Programming  /  Control Flow  /  If...Else

If...Else

if...else lets your code make decisions — run one block of code when a condition is true, and a different block when it is not.

Basic if Statement

R Code
age <- 20

if (age >= 18) {
  print("You are an adult.")
}
Output
[1] "You are an adult."

if...else

R Code
age <- 15

if (age >= 18) {
  print("You are an adult.")
} else {
  print("You are a minor.")
}
Output
[1] "You are a minor."

if...else if...else Chains

Chain multiple conditions to handle more than two outcomes.

R Code
score <- 72

if (score >= 90) {
  grade <- "A"
} else if (score >= 75) {
  grade <- "B"
} else if (score >= 60) {
  grade <- "C"
} else {
  grade <- "F"
}

grade
Output
[1] "C"

Vectorised Alternative: ifelse()

Regular if() only works on a single TRUE/FALSE value. To apply a condition to an entire vector at once, use ifelse() instead.

R Code
scores <- c(45, 82, 91, 60)
result <- ifelse(scores >= 60, "Pass", "Fail")
result
Output
[1] "Fail" "Pass" "Pass" "Pass"
⚠ Common Mistake
Calling if(scores >= 60) when scores is a vector of length greater than one raises an error in modern R ("the condition has length > 1"). Whenever your condition involves a whole column of data, reach for ifelse() instead of if().

Advanced: Nested Conditions

🚀 Advanced Example
Conditions can be nested to check multiple, related criteria - useful for multi-factor eligibility checks.
R Code
age <- 17; has_id <- TRUE

if (age >= 18) {
  print("Entry allowed.")
} else {
  if (has_id) {
    print("Underage but has ID - manager review needed.")
  } else {
    print("Entry denied.")
  }
}
Output
[1] "Underage but has ID - manager review needed."

Key Points

  • if() tests exactly one TRUE/FALSE value at a time.
  • Chain else if for more than two possible outcomes.
  • Use ifelse(), not if(), when the condition comes from a whole vector or data frame column.