Decision Making in R Programming - if, if-else, if-else-if ladder, nested if-else, and switch

Last Updated : 7 Jun, 2025

Decision making in programming allows us to control the flow of execution based on specific conditions. In R, various decision-making structures help us execute statements conditionally. These include:

  1. if statement
  2. if-else statement
  3. if-else-if ladder
  4. nested if-else statement
  5. switch statement

1. if Statement

The if statement evaluates a condition. If the condition is TRUE, the associated statement is executed. If the condition is FALSE, the statement is skipped.

Syntax:

if (condition) {

# execute this statement

}

Flow Chart:                        

if-statement-flowchart

Example: 

R
a <- 76
b <- 67

if (a > b) {
  c <- a - b
  print("condition a > b is TRUE")
  print(paste("Difference between a, b is:", c))
}

if (a < b) {
  c <- a - b
  print("condition a < b is TRUE")
  print(paste("Difference between a, b is:", c))
}

Output: 

[1] "condition a > b is TRUE"
[1] "Difference between a, b is: 9"

2. if-else Statement

The if-else statement executes one block if the condition is TRUE and another if it is FALSE.

Syntax:

if (condition) {

# execute this statement

} else {

# execute this statement

}

Flow Chart:

if-else-statement-flowchart

Example : 

r
a <- 67
b <- 76

if (a > b) {
  c <- a - b
  print("condition a > b is TRUE")
  print(paste("Difference between a, b is:", c))
} else {
  c <- a - b
  print("condition a > b is FALSE")
  print(paste("Difference between a, b is:", c))
}

Output: 

[1] "condition a > b is FALSE"
[1] "Difference between a, b is : -9"

3. if-else-if Ladder

This structure chains multiple conditions together. Each condition is evaluated in sequence. If a condition is TRUE, its block is executed. Otherwise, the next condition is checked.

Syntax:

if (condition1) {

# execute this statement

} else if (condition2) {

# execute this statement

} else {

# execute this statement

}

Flow Chart: 

if-else-if-ladder-flowchart

Example : 

r
a <- 67
b <- 76
c <- 99

if (a > b && b > c)