Week 5: Making Decisions in R
Learn to control the flow of your R scripts using conditional statements.
Explore Chapter 5`else if` and `else` Statements.
Often, you want to check multiple conditions or provide a default action if the initial `if` condition is false.
The `else` Statement
An `else` statement provides code to execute if the `if` condition is `FALSE`.
if (condition) {
# Execute this if condition is TRUE
} else {
# Execute this if condition is FALSE
}
The `else if` Statement
You can check additional conditions using `else if`. The conditions are checked sequentially. As soon as one condition (`if` or `else if`) is `TRUE`, its block is executed, and the remaining `else if` and `else` blocks are skipped.
if (condition1) {
# Block 1: Executes if condition1 is TRUE
} else if (condition2) {
# Block 2: Executes if condition1 is FALSE and condition2 is TRUE
} else if (condition3) {
# Block 3: Executes if 1&2 are FALSE and condition3 is TRUE
} else {
# Block 4: Executes if conditions 1, 2, and 3 are all FALSE
}
Example
score <- 75
if (score >= 90) {
grade <- "A"
} else if (score >= 80) {
grade <- "B"
} else if (score >= 70) {
grade <- "C"
} else if (score >= 60) {
grade <- "D"
} else {
grade <- "F"
}
print(paste("The grade is:", grade)) # Output: [1] "The grade is: C"