6  If-Else Statements

6.1 Objectives

  • Write conditional statements using if
  • Use if...else and else if
  • Apply vectorized logic using ifelse()
  • Understand when to use each structure

6.2 If Statements

Basic syntax:

if (condition){
  # do task
}

Example:

a <- 5

if (a > 3){
  print("a is bigger than 3")
}
[1] "a is bigger than 3"

The code inside the braces runs only if the condition is TRUE.

6.3 Else Statements

Use else to define what happens when the condition is FALSE.

a <- 5

if (a > 3){
  print("a is bigger than 3")
} else {
  print("a is NOT bigger than 3")
}
[1] "a is bigger than 3"

Only one block will execute.

6.4 Else-If Statements

Use else if to test multiple conditions.

a <- 5

if (a > 3){
  print("a is bigger than 3")
} else if (a == 3) {
  print("a equals 3")
} else {
  print("a is less than 3")
}
[1] "a is bigger than 3"

R checks conditions from top to bottom and stops when one is TRUE.

6.5 The ifelse() Function

ifelse() is a vectorized version of if.

Syntax:

ifelse(condition, value_if_true, value_if_false)

Example:

a <- 5

ifelse(a > 3,
       "a is bigger than 3",
       "a is not bigger than 3")
[1] "a is bigger than 3"

Unlike if, ifelse() works well on vectors:

x <- 1:5
ifelse(x > 3, "big", "small")
[1] "small" "small" "small" "big"   "big"  

Use ifelse() when working with vectors or data frame columns.