Switch case in R

The switch() function in R provides a way to perform conditional branching based on the value of an expression. It's akin to a series of "if-else" statements but is more concise when dealing with multiple conditions. Here's a detailed explanation with examples:

Syntax:
result <- switch(expr, value1 = statement1, value2 = statement2, ... valueN = statementN, default = default_statement)

Simple Switch..Case in R

day <- "Monday" message <- switch(day, "Monday" = "Start of the week", "Tuesday" = "Second day", "Wednesday" = "Middle of the week", "Thursday" = "Almost there", "Friday" = "End of the week", "Weekend" = "Rest time", default = "Unknown day") print(message) #Output:"Start of the week"

In the above example, the switch() function evaluates the value of the day variable and selects the corresponding message based on the provided cases. If the value of day matches any of the cases, the corresponding message is assigned to the message variable; otherwise, the default statement is used.

Using Switch in a Function

get_message <- function(day) { message <- switch(day, "Monday" = "Start of the week", "Tuesday" = "Second day", "Wednesday" = "Middle of the week", "Thursday" = "Almost there", "Friday" = "End of the week", "Weekend" = "Rest time", default = "Unknown day") return(message) } day1 <- "Thursday" day2 <- "Sunday" print(get_message(day1)) print(get_message(day2)) #Output: "Almost there" NULL

In the above example, the switch() function is utilized within a custom function get_message() to provide the same functionality. The function can be reused to get messages for different days.

Conclusion

switch() is particularly useful when you have a single expression to evaluate and you want to choose from a set of options based on its value. It streamlines code, making it more concise and readable, especially when dealing with multiple cases.