Switch statements in R provide an efficient way to execute different code blocks based on the value of an expression. They offer a cleaner alternative to multiple if-else statements when dealing with discrete cases.
The basic syntax of an R switch statement is:
switch(expression,
case1 = result1,
case2 = result2,
...,
default = default_result
)
Here's how it works:
expression
is evaluated first.default
result (if provided) is returned.fruit <- "apple"
result <- switch(fruit,
"apple" = "It's red and crunchy",
"banana" = "It's yellow and soft",
"orange" = "It's orange and juicy",
"Unknown fruit"
)
print(result) # Output: It's red and crunchy
Switch statements can also work with numeric expressions:
day_number <- 3
day_name <- switch(day_number,
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Weekend"
)
print(day_name) # Output: Wednesday
For more complex control flow, R offers other options:
Understanding switch statements is crucial for efficient R programming. They complement other control structures and can significantly improve code readability when used appropriately.