R Core Language Concepts
Estimated reading: 3 minutes 32 views

🔀 R If…Else – Decision Making in R Programming


🧲 Introduction – Control Your Code with If…Else Statements

In real-world data analysis, decisions are everywhere: if a score is above 90, label it as “Excellent”; if a dataset is empty, stop execution. In R, we handle these situations using if, else if, and else statements.

Decision-making structures allow your R program to execute certain blocks of code conditionally, based on logical tests. This helps create dynamic, flexible, and intelligent R scripts.

🎯 In this guide, you’ll learn:

  • Syntax of if, else, and else if
  • Nested and vectorized decision-making with ifelse()
  • Common patterns used in data classification, warnings, and loops

🧾 Basic Syntax of If…Else in R

if (condition) {
  # code if TRUE
} else if (another_condition) {
  # code if second condition TRUE
} else {
  # code if all conditions FALSE
}

✅ Example 1: Basic If Condition

score <- 85

if (score > 80) {
  print("Great score!")
}

🧾 Output:

[1] "Great score!"

✅ Example 2: If…Else Condition

score <- 65

if (score >= 70) {
  print("Pass")
} else {
  print("Fail")
}

🧾 Output:

[1] "Fail"

✅ Example 3: If…Else If…Else Chain

score <- 90

if (score >= 90) {
  print("Grade: A")
} else if (score >= 80) {
  print("Grade: B")
} else if (score >= 70) {
  print("Grade: C")
} else {
  print("Grade: D")
}

🧾 Output:

[1] "Grade: A"

🔄 Using ifelse() – Vectorized Decision Making

The ifelse() function works element-wise on vectors and is very efficient.

marks <- c(80, 45, 70, 55, 90)
result <- ifelse(marks >= 60, "Pass", "Fail")
print(result)

🧾 Output:

[1] "Pass" "Fail" "Pass" "Fail" "Pass"

✅ Syntax:

ifelse(condition, value_if_TRUE, value_if_FALSE)

🔁 Nested If Statements

You can nest if statements for more complex decision trees.

temp <- 32

if (temp > 30) {
  if (temp < 40) {
    print("Hot but not extreme")
  } else {
    print("Extreme heat warning!")
  }
}

🚫 Using if with Logical Vectors (Caution!)

x <- c(TRUE, FALSE)
if (x) {
  print("Works?")
}

🔺 This will throw a warning, because if expects a single logical value.

✅ Instead, use ifelse() for vectorized conditions.


📌 Summary – Recap & Next Steps

if…else statements allow you to control program flow based on dynamic logic. Whether you’re assigning grades, filtering rows, or generating warnings, conditional logic makes your R scripts smarter.

🔍 Key Takeaways:

  • Use if, else if, and else for decision branches
  • Always wrap conditions in parentheses ()
  • Use ifelse() for element-wise conditional operations
  • Don’t use regular if with vectors—use ifelse() instead
  • Nested if is possible and powerful for layered logic

⚙️ Real-World Relevance:
Decision-making is essential in tasks like data validation, quality control, conditional labeling, algorithm design, and user feedback generation in R applications.


❓ FAQs – R If…Else

❓ Can I use multiple conditions in if?
✅ Yes, combine them using & (AND) or | (OR):

if (age > 18 & age < 60) { print("Adult") }

❓ What’s the difference between if and ifelse()?
if evaluates a single condition. ifelse() handles vectors:

ifelse(c(TRUE, FALSE), "Yes", "No")  # Vectorized

❓ How to write a ternary-style one-liner in R?
✅ Use ifelse():

ifelse(x > 10, "High", "Low")

❓ Can I write else on the next line in R?
⚠️ No. Always place else immediately after the closing brace of if.

# Correct
if (x > 5) {
  print("Hi")
} else {
  print("Bye")
}

❓ Can I skip else and only use if?
✅ Yes, else is optional.


Share Now :

Leave a Reply

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

Share

R — If…Else / Decision Making

Or Copy Link

CONTENTS
Scroll to Top