R Else If Ladder

An else-if ladder extends the basic if-else by adding multiple conditions in sequence. R evaluates each condition from top to bottom and executes only the first matching block. Once a match is found, all remaining conditions are skipped.

Syntax

if (condition1) {
  # runs when condition1 is TRUE
} else if (condition2) {
  # runs when condition2 is TRUE
} else if (condition3) {
  # runs when condition3 is TRUE
} else {
  # runs when none of the above are TRUE
}

Flow Diagram

     condition1?
         │ NO
         ▼
     condition2?
         │ NO
         ▼
     condition3?
         │ NO
         ▼
      else block

Evaluation stops the moment any condition is TRUE. The rest of the ladder is not checked.

Example: Exam Grade System

score <- 76

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

cat("Grade:", grade, "\n")

Output:

Grade: B

For score 76: First condition (≥90) fails. Second condition (≥75) passes. Grade is set to "B". The remaining conditions are never checked.

Order Matters

# WRONG order — always outputs "C" for any score above 60
score <- 92
if (score >= 60) {
  cat("C")             # This catches 92 first!
} else if (score >= 75) {
  cat("B")
} else if (score >= 90) {
  cat("A")             # Never reached
}

# CORRECT order — most restrictive condition first
if (score >= 90) {
  cat("A")
} else if (score >= 75) {
  cat("B")
} else if (score >= 60) {
  cat("C")
}

Practical Example: Electricity Bill Calculator

units_consumed <- 320

if (units_consumed <= 100) {
  rate <- 2.00
} else if (units_consumed <= 200) {
  rate <- 3.50
} else if (units_consumed <= 400) {
  rate <- 5.00
} else {
  rate <- 7.00
}

bill <- units_consumed * rate
cat("Units:", units_consumed, "\n")
cat("Rate per unit: ₹", rate, "\n")
cat("Total bill: ₹", bill, "\n")

Output:

Units: 320
Rate per unit: ₹ 5
Total bill: ₹ 1600

Using dplyr::case_when() for Vectorized Ladders

For applying an else-if ladder to an entire column in a data frame, use case_when() from dplyr:

library(dplyr)
scores <- c(92, 76, 58, 43, 85)

grades <- case_when(
  scores >= 90 ~ "A",
  scores >= 75 ~ "B",
  scores >= 60 ~ "C",
  scores >= 45 ~ "D",
  TRUE          ~ "F"
)
print(grades)
# [1] "A" "B" "C" "D" "B"

Else-if ladders handle complex, multi-outcome decisions cleanly. Keep conditions in logical order (most specific first), always include an else block as a safety net, and use case_when() when applying the same logic to a whole vector or column.

Leave a Comment

Your email address will not be published. Required fields are marked *