Use else if to check multiple conditions in
sequence.
quantity <- 10
if (quantity < 20) {
print("Not enough for today.")
} else if (quantity > 20 && quantity <= 30) {
print("Average day.")
} else {
print("What a great day!")
}## [1] "Not enough for today."
Note: - && is the scalar “AND” operator
typically used in if() statements; & is
vectorized and compares element-by-element.
Imagine three product categories with different VAT rates:
| Category | Products | VAT |
|---|---|---|
| A | Books, magazines, newspapers, … | 8% |
| B | Vegetables, meat, beverages, … | 10% |
| C | T-shirts, jeans, pants, … | 20% |
We can apply the correct VAT rate with an if / else if
chain:
category <- "A"
price <- 10
if (category == "A") {
total <- price * 1.08
cat("VAT rate: 8%.\nTotal price:", total, "\n")
} else if (category == "B") {
total <- price * 1.10
cat("VAT rate: 10%.\nTotal price:", total, "\n")
} else {
total <- price * 1.20
cat("VAT rate: 20%.\nTotal price:", total, "\n")
}## VAT rate: 8%.
## Total price: 10.8
If you need to apply conditions to an entire vector (not just a
single value), you typically use ifelse() (base R) or
dplyr::if_else() (type-stable).
A work by Gianluca Sottile
gianluca.sottile@unipa.it