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)

R

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)

R

Form 3 – One-liner (very common in quick scripts)

R

2. Real-Life Examples – Hyderabad Style

Example 1 – Simple temperature check

R

Example 2 – Grading system (multiple else if)

R

Example 3 – Check for missing data before calculation

R

Example 4 – One-liner style (very common in data cleaning)

R

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).

R

Modern 2026 favorite — dplyr::case_when() (much more readable):

R

4. Common Beginner Mistakes & Fixes

Mistake 1 — Using vector in if condition

R

Fix → use any(), all(), or ifelse()

R

Mistake 2 — Forgetting else when needed

Mistake 3 — Missing curly braces with multi-line code

R

Fix → always use { } when more than one line

Mistake 4 — Using = instead of == in condition

R

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!)

R

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! ☕🚦🚀

You may also like...

Leave a Reply

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