R If Else Statement

An if-else statement adds a second path to a decision. When the condition is TRUE, the first block runs. When it is FALSE, the else block runs. Exactly one of the two blocks always executes — never both, never neither.

Syntax

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

Flow Diagram

              condition?
                  │
         ┌────────┴────────┐
         ▼                 ▼
       TRUE              FALSE
         │                 │
    if { }           else { }
    runs               runs
         │                 │
         └────────┬────────┘
                  ▼
           Program continues

Basic Example

marks <- 55

if (marks >= 50) {
  cat("Result: PASS\n")
} else {
  cat("Result: FAIL\n")
}

Output:

Result: PASS

Practical Example: Login Check

entered_password <- "secure123"
correct_password <- "secure123"

if (entered_password == correct_password) {
  cat("Login successful. Welcome!\n")
} else {
  cat("Incorrect password. Access denied.\n")
}

ifelse() — Vectorized Version

The ifelse() function applies an if-else decision to every element of a vector at once. This is extremely useful in data analysis.

scores <- c(85, 40, 92, 55, 30, 78)

results <- ifelse(scores >= 50, "Pass", "Fail")
print(results)

Output:

[1] "Pass" "Fail" "Pass" "Pass" "Fail" "Pass"
Diagram:
scores:   85   40   92   55   30   78
         ≥50?  ≥50? ≥50? ≥50? ≥50? ≥50?
          │    │    │    │    │    │
         Pass Fail Pass Pass Fail Pass

Using if-else to Assign Values

speed_kmh <- 85

fine_amount <- if (speed_kmh > 80) 500 else 0
cat("Fine: ₹", fine_amount, "\n")

Output:

Fine: ₹ 500

Nested if-else

bmi <- 27.5

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

cat("BMI Category:", category, "\n")

Output:

BMI Category: Overweight

Key Rules

  • The else block must start on the same line as the closing } of the if block
  • Each if-else pair handles exactly one TRUE/FALSE condition
  • For multiple conditions, use else-if (covered in the next topic)
  • For vectorized operations, prefer ifelse() over a plain if-else
# Correct placement of else
if (x > 0) {
  cat("positive")
} else {               # ← else on SAME LINE as closing }
  cat("not positive")
}

# WRONG — this causes an error
if (x > 0) {
  cat("positive")
}
else {                 # ← else on NEW LINE = ERROR
  cat("not positive")
}

The if-else structure is the most fundamental decision tool in programming. Almost every real R program contains dozens of them. Pair this with ifelse() for vector operations and you handle most conditional scenarios in data analysis efficiently.

Leave a Comment

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