Chapter 18: R If … Else
if … else
This is how you tell the computer: “If this condition is true → do this, otherwise → do that.”
It’s used everywhere:
- Decide whether to show a warning
- Apply different calculations depending on a value
- Filter or transform data conditionally
- Stop a function early if something is wrong
I’m going to explain it like we’re sitting together with RStudio open — slowly, step by step, with many realistic examples, common mistakes, and clean modern style (2026 way).
1. Basic Syntax – Three Main Forms
R has three common ways to write if-else:
Form 1 – Classic if … else (most readable)
|
0 1 2 3 4 5 6 7 8 9 10 |
if (condition) { # code to run if condition is TRUE } else { # code to run if condition is FALSE } |
Important rules:
- condition must be a single logical value (TRUE or FALSE) — not a vector!
- Curly braces { } are required when more than one line inside
- You can omit { } for single-line bodies (but many people always use them for clarity)
Form 2 – if … else if … else (multiple conditions)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if (condition1) { # ... } else if (condition2) { # ... } else if (condition3) { # ... } else { # none of the above } |
Form 3 – One-liner (very common in quick scripts)
|
0 1 2 3 4 5 6 |
if (temp > 30) print("It's hot!") else print("Nice weather") |
2. Real-Life Examples – Hyderabad Style
Example 1 – Simple temperature check
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
temp_now <- 31.2 if (temp_now > 30) { cat("It's a hot day in Hyderabad! 🌶️\n") cat("Drink water and stay indoors if possible.\n") } else { cat("Pleasant weather today.\n") } |
Example 2 – Grading system (multiple else if)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
marks <- 78 if (marks >= 90) { grade <- "A+" } else if (marks >= 80) { grade <- "A" } else if (marks >= 70) { grade <- "B" } else if (marks >= 50) { grade <- "C" } else { grade <- "F" } cat("Your grade is:", grade, "\n") |
Example 3 – Check for missing data before calculation
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
student_scores <- c(92, NA, 85, 68, 78) if (any(is.na(student_scores))) { cat("Warning: Missing scores detected. Using only complete cases.\n") avg <- mean(student_scores, na.rm = TRUE) } else { avg <- mean(student_scores) } cat("Average score:", round(avg, 1), "\n") |
Example 4 – One-liner style (very common in data cleaning)
|
0 1 2 3 4 5 6 7 8 9 |
age <- 17 status <- if (age >= 18) "Adult" else "Minor" print(status) # "Minor" |
3. The Vectorized Alternative – ifelse() (Very Important!)
if … else works only with single TRUE/FALSE.
If you have a vector and want to apply different logic to each element → use ifelse() (base R) or case_when() (dplyr).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
temps <- c(28.5, 31.2, 29.8, 35.0, 27.9) # Wrong – this will error or only use first element! # if (temps > 30) "Hot" else "Okay" # Correct – vectorized comfort_level <- ifelse(temps > 30, "Hot", "Okay") print(comfort_level) # "Okay" "Hot" "Okay" "Hot" "Okay" # With more categories comfort_level <- ifelse(temps > 32, "Very Hot", ifelse(temps > 30, "Hot", ifelse(temps > 25, "Pleasant", "Cool"))) |
Modern 2026 favorite — dplyr::case_when() (much more readable):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
library(dplyr) comfort_level <- case_when( temps > 32 ~ "Very Hot", temps > 30 ~ "Hot", temps > 25 ~ "Pleasant", TRUE ~ "Cool" # default case (like else) ) print(comfort_level) |
4. Common Beginner Mistakes & Fixes
Mistake 1 — Using vector in if condition
|
0 1 2 3 4 5 6 7 |
# Wrong if (marks >= 50) print("Passed") # only uses first element! |
Fix → use any(), all(), or ifelse()
|
0 1 2 3 4 5 6 7 8 |
if (any(marks < 50)) { cat("Some students failed!\n") } |
Mistake 2 — Forgetting else when needed
Mistake 3 — Missing curly braces with multi-line code
|
0 1 2 3 4 5 6 7 8 9 |
# Wrong – only first line runs if true if (temp > 30) cat("Hot!\n") cat("Drink water!\n") # this always runs! |
Fix → always use { } when more than one line
Mistake 4 — Using = instead of == in condition
|
0 1 2 3 4 5 6 |
if (city = "Hyderabad") { ... } # assignment → wrong! |
5. Quick Cheat-Sheet
- Single value condition → if (cond) { … } else { … }
- Multiple conditions → else if (…)
- Vector of conditions → ifelse(test, yes, no) or case_when(…)
- Default case in case_when() → TRUE ~ “default value”
- Check existence → any(), all(), is.na(), !is.na()
- Short-circuit && / || → only inside if/while
Your Mini Practice (Copy → Run!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# Mock Hyderabad traffic light decision light_color <- "Yellow" speed_kmh <- 45 if (light_color == "Green") { action <- "Go" } else if (light_color == "Yellow") { if (speed_kmh > 20) { action <- "Slow down carefully" } else { action <- "Prepare to stop" } } else if (light_color == "Red") { action <- "Stop" } else { action <- "Invalid color" } cat("Traffic light:", light_color, "→", action, "\n") |
Now try changing light_color and speed_kmh and see what happens!
Ready for more?
- Want to practice case_when() with real data frame?
- Combine if-else with loops?
- Or move to for / while loops next?
Just tell me — whiteboard is still clean and ready! ☕🚦🚀
