01 / 21

Nested
Conditionals in R

Master the art of decision trees in code: write nested \(\text{if}\)/\(\text{else}\) structures and handle boundary conditions like a pro.

R Programming

What Are Conditionals?

A conditional statement lets your program make decisions. In R, the \(\text{if}\) statement evaluates a logical expression: if it is TRUE, a block of code runs; otherwise, R can execute an alternative block.

if (condition) {
  # runs when condition is TRUE
} else {
  # runs when condition is FALSE
}

Why Do We Nest Conditionals?

Real-world decisions are rarely binary. Nested conditionals place one \(\text{if}\)/\(\text{else}\) inside another, creating a decision tree that can handle multiple outcomes based on several criteria.

Single if/else
Handles 2 outcomes: TRUE or FALSE.
Nested if/else
Handles 3+ outcomes by branching further at each level.
Real Example
Grading: A, B, C, D, or F requires at least 4 branches.

Visualizing a Decision Tree

\( \text{score} \geq 60? \)
TRUE FALSE
\( \text{score} \geq 90? \)
Print "F" TRUE FALSE Print "A"
\( \text{score} \geq 80? \)
TRUE Print "B" FALSE
\( \text{score} \geq 70? \)
TRUE Print "C" FALSE Print "D"

The Nested if/else Pattern

R Syntax
if (condition_1) {
  # Block A
} else if (condition_2) {
  # Block B
} else if (condition_3) {
  # Block C
} else {
  # Default block (boundary catch-all)
}

Handling Boundary Conditions

A boundary condition is a value that sits right at the edge of two categories. For example, if a passing score is 60, what happens when someone scores exactly 60? Your conditional must define whether \( \geq \) or \( > \) is the correct comparison.

\( \geq \) (inclusive)
Score of 60 passes. Use \( \geq \)
\( > \) (exclusive)
Score of 60 fails. Use \( > \)

if/else vs else if vs switch

Nested if/else else if chain switch()
Use case Complex, multi-level logic Linear multi-way branch Exact value matching
Condition type Any logical expression Any logical expression Single value only
Readability Decreases with depth Good for 3-5 branches Excellent for many values
Boundary handling Full control Full control Not applicable

How to Write Nested Conditionals

1
Identify all outcomes. List every possible result (e.g., grades A through F).
2
Define boundary values. Determine the exact cutoff for each category and whether it is inclusive (\( \geq \)) or exclusive (\( > \)).
3
Order conditions logically. Check the most restrictive condition first (e.g., \( \text{score} \geq 90 \) before \( \text{score} \geq 80 \)).
4
Always include a final \(\text{else}\). This is your safety net that catches anything unexpected.
5
Test boundary values. Feed in the exact cutoff numbers to verify the correct branch fires.

Example 1: Letter Grade

R Code
score <- 85

if (score >= 90) {
  cat("A")
} else if (score >= 80) {
  cat("B")
} else if (score >= 70) {
  cat("C")
} else if (score >= 60) {
  cat("D")
} else {
  cat("F")
}

Example 2: Ticket Price Calculator

R Code: Nested Logic
age <- 15
is_student <- TRUE

if (age < 5) {
  price <- 0       # Free for under 5
} else if (age <= 17) {
  # Youth: check student status
  if (is_student) {
    price <- 5   # Student discount
  } else {
    price <- 8   # Youth non-student
  }
} else {
  price <- 12     # Adult full price
}

Example 3: Boundary Edge Cases

Testing the Edges
temp <- 0  # Boundary: exactly 0

if (temp > 0) {
  cat("Above freezing")
} else if (temp == 0) {
  cat("At freezing point")
} else {
  cat("Below freezing")
}

Example 4: BMI Classifier

R Code: Order Matters
bmi <- 24.9

if (bmi < 18.5) {
  category <- "Underweight"
} else if (bmi < 25) {
  category <- "Normal"
} else if (bmi < 30) {
  category <- "Overweight"
} else {
  category <- "Obese"
}
cat(category)  # "Normal"

Execution Flow in Detail

Start condition_1 TRUE? TRUE Block A FALSE condition_2 TRUE? TRUE Block B FALSE condition_3 TRUE? TRUE Block C FALSE else (Default)

Deep Nesting vs Flat Chains

Deep Nesting
\(\text{if (...) \{ if (...) \{ if (...) \{ ... \} \} \}}\)
Hard to read. Easy to lose track of which \(\text{else}\) matches which \(\text{if}\). Limit to 2-3 levels.
Flat else if Chain
\(\text{if (...) \{\} else if (...) \{\} else if (...) \{\}}\)
Easier to scan. Each branch is at the same indentation level. Prefer this when possible.

Common Mistakes

✕ Wrong Order
Checking \( \geq 60 \) before \( \geq 90 \): everyone \( \geq 60 \) matches the first branch, so "A" students get "D".
✕ Missing else
No final \(\text{else}\) means unexpected values (like \(\text{NA}\) or negative numbers) produce no output at all.
✕ Using \( = \) Instead of \( == \)
Writing \(\text{if (x = 5)}\) is assignment, not comparison. R will throw an error. Use \( == \).

Summary Cheat Sheet

Concept Key Point R Syntax
Simple conditional Two outcomes \(\text{if / else}\)
Multi-way branch 3+ outcomes, flat \(\text{if / else if / else}\)
Nested conditional if inside another if \(\text{if \{ if \{ \} \}}\)
Boundary: inclusive Edge value included \( \geq \) or \( \leq \)
Boundary: exclusive Edge value excluded \( > \) or \( < \)
Safety net Always end with else \(\text{else \{ default \}}\)

Question 1 of 5

What is printed when the following R code runs?

Question 2 of 5

Which operator should you use if a score of exactly 60 should pass?

Question 3 of 5

What happens if you check \( \geq 60 \) before checking \( \geq 90 \) in an else if chain?

Question 4 of 5

What is printed by this nested conditional?

Question 5 of 5

Why is it important to include a final \(\text{else}\) block at the end of an if/else if chain?