Life is full of decisions โ and so is code. In R, you make decisions using if and else statements. They let your script choose a path based on whether a condition is true or false. You'll also meet ifelse(), which is R's vectorized way of handling conditions โ super handy when you're working with whole columns of data at once.
if and else
The basic structure is simple: write if, put a condition in parentheses, and wrap the action in curly braces. Add else to handle the "otherwise" case, and else if for extra branches.
x <- 10
if (x > 5) {
print("x is greater than 5")
} else {
print("x is 5 or less")
}
# Multiple branches
y <- 0
if (y > 0) {
print("Positive")
} else if (y < 0) {
print("Negative")
} else {
print("Zero")
}
Try it Yourself โ
Vectorized ifelse()
Regular if works on a single value. But what if you have a whole vector and want to check each element? That's where ifelse() shines. It takes a condition, a value if true, and a value if false โ and it recycles them across your entire vector.
scores <- c(55, 82, 91, 47, 73)
grades <- ifelse(scores >= 70, "Pass", "Fail")
print(grades)
Try it Yourself โ
Nested Conditions
You can nest ifelse() calls to handle multiple categories. Just chain another ifelse() inside the "false" spot.
marks <- c(45, 72, 88, 60, 95)
result <- ifelse(marks >= 80, "Distinction",
ifelse(marks >= 60, "Merit",
ifelse(marks >= 40, "Pass", "Fail")))
print(result)
Try it Yourself โ