In R, there isn’t a traditional switch statement like you might find in some other programming languages. Instead, R offers a functional alternative called the switch function, which allows you to choose between several expressions or actions based on a single integer or character value. The switch function works in a similar way to a switch statement, but it’s a function rather than a control flow statement.
Here’s the basic syntax of the switch function:
switch(EXPR, CASE1, CASE2, …, DEFAULT)
EXPR: The expression whose value you want to match against the cases.
CASE1, CASE2, …: The values to compare against EXPR. These are the possible cases.
DEFAULT (optional): The default value or action to be taken if none of the cases match EXPR.
Here’s an example of how to use the switch function:
day <- 3
weekday <- switch(
day,
“Sunday”,
“Monday”,
“Tuesday”,
“Wednesday”,
“Thursday”,
“Friday”,
“Saturday”,
“Invalid day”
)
cat(“Today is”, weekday)
In this example, the day variable is set to 3, and the switch function matches it against the cases “Sunday”, “Monday”, “Tuesday”, and so on. Since day is 3, it matches the “Tuesday” case, and the result is assigned to the weekday variable. If day doesn’t match any of the cases, it falls back to the “Invalid day” case.
You can use the switch function to select one of several options based on the value of an expression, but keep in mind that it works primarily with character or integer values. If you need more complex conditional logic or comparisons, you might want to use a combination of if, else if, and else statements.