R If...Else
Programs need to make decisions. The if statement runs a block of code only when a condition is TRUE.
temperature <- 28
if (temperature > 25) {
print("It's a hot day")
}[1] "It's a hot day"
The condition goes inside parentheses, and the code to run goes inside braces.
else and else if
Add else for the alternative, and chain else if for more cases. R checks the conditions from top to bottom and runs the first block whose condition is TRUE:
grade <- function(score) {
if (score >= 90) {
"A"
} else if (score >= 75) {
"B"
} else if (score >= 50) {
"C"
} else {
"F"
}
}
grade(95)
grade(80)
grade(42)[1] "A"
[1] "B"
[1] "F"
Note: In a script,
elsemust be on the same line as the closing}of theifblock. If}ends a line, R considers theiffinished and a followingelseon a new line is a syntax error.
if returns a value
if is an expression: it evaluates to the value of the branch that ran. You can assign its result directly:
stock <- 0
status <- if (stock > 0) "available" else "sold out"
status[1] "sold out"
Nested conditions and logical operators
Combine conditions with && and ||, or nest if statements:
age <- 20
member <- TRUE
if (age >= 18 && member) {
cat("Full access\n")
} else if (age >= 18) {
cat("Please sign up\n")
} else {
cat("Too young\n")
}Full access
The condition must be a single TRUE or FALSE
if needs exactly one logical value. A missing value or a vector of length 2 is an error:
x <- c(3, 8)
if (x > 5) print("big")Error in if (x > 5) print("big") : the condition has length > 1
To ask "is any/every element bigger?", use any(x > 5) or all(x > 5).
ifelse(): vectorised if
To choose a value for each element of a vector, use ifelse(test, yes, no):
temps <- c(12, 25, 31, 18)
ifelse(temps > 20, "warm", "cold")
scores <- c(45, 72, 90)
ifelse(scores >= 50, "pass", "fail")[1] "cold" "warm" "warm" "cold"
[1] "fail" "pass" "pass"
switch()
When you compare one value against many options, switch() is more compact than a long else if chain. The last unnamed argument is the default:
unit_name <- function(code) {
switch(code,
km = "kilometres",
mi = "miles",
m = , # falls through to the next value
metre = "metres",
"unknown unit")
}
unit_name("km")
unit_name("m")
unit_name("ft")[1] "kilometres"
[1] "metres"
[1] "unknown unit"
Test yourself
What does if (5 > 3) "yes" else "no" return?
- "no"
- "yes"
- TRUE
- NULL
Which function picks a value for every element of a vector?
- if
- switch
- ifelse
- while
What happens with if (c(TRUE, FALSE)) ... in R 4.2+?
- Only the first element is used
- An error: the condition has length > 1
- Both branches run
- It returns NA