R If … Else

🔀 R If … Else

In R, the if … else statement is used for decision making.

It allows your program to execute different code blocks based on conditions.


🔹 1. Basic if Statement

Syntax:

if (condition) {
# code executes if condition is TRUE
}

Example:

age <- 20

if (age >= 18) {
print(“Eligible to vote”)
}


🔹 2. if … else Statement

Syntax:

if (condition) {
# executes if TRUE
} else {
# executes if FALSE
}

Example:

age <- 16

if (age >= 18) {
print(“Eligible to vote”)
} else {
print(“Not eligible to vote”)
}


🔹 3. else if Statement (Multiple Conditions)

Syntax:

if (condition1) {
# code
} else if (condition2) {
# code
} else {
# code
}

Example:

marks <- 75

if (marks >= 90) {
print(“Grade A”)
} else if (marks >= 60) {
print(“Grade B”)
} else {
print(“Grade C”)
}


🔹 4. Nested if … else

An if inside another if.

num <- 10

if (num > 0) {
if (num %% 2 == 0) {
print(“Positive Even Number”)
} else {
print(“Positive Odd Number”)
}
}


🔹 5. Logical Conditions in if

You can use logical operators (&, |, &&, ||).

age <- 25
has_id <- TRUE
if (age >= 18 & has_id) {
print(“Entry allowed”)
}

🔹 6. ifelse() Function (Vectorized)

Used when working with vectors.

Syntax:

ifelse(condition, value_if_true, value_if_false)

Example:

x <- c(5, 15, 25)

ifelse(x > 10, “Big”, “Small”)

Output:

[1] "Small" "Big" "Big"

✔ Faster and cleaner for vectors


🔹 7. Common Mistakes ❌

❌ Using = instead of ==

if (x = 10) # wrong

✅ Correct:

if (x == 10)

❌ Forgetting braces for multiple lines


🔹 8. Best Practices ✔

  • Always use curly braces {}

  • Keep conditions simple and readable

  • Use ifelse() for vector operations


📌 Summary

  • if checks a condition

  • else runs when condition is FALSE

  • else if handles multiple conditions

  • ifelse() works best with vectors

You may also like...