switch()
Statement in R
The switch()
function in R is used to select one of many alternatives based on the value of an expression. It works like a multi-way branch, similar to switch
in other programming languages.
switch(EXPR, case1 = value1, case2 = value2, case3 = value3, ... default_value)
Explanation:
EXPR
: The expression or value to test (usually a character or numeric).case1, case2, ...
: Named options to match against EXPR
.value1, value2, ...
: Corresponding values or expressions returned when a case matches.default_value
: Optional; returned if none of the cases match.Suppose you want to print a message based on the selected fruit:
fruit <- "apple" message <- switch(fruit, apple = "You selected Apple 🍎", banana = "You selected Banana 🍌", orange = "You selected Orange 🍊", "Unknown fruit" ) print(message)
Output: You selected Apple 🍎
You can also use numeric values in switch()
. If the expression is numeric, the matching is done by position:
choice <- 2 result <- switch(choice, "First option", "Second option", "Third option" ) print(result)
Output: Second option
EXPR
is a character, it matches the names of the cases.EXPR
is numeric, it selects the case by its position (1-based).switch()
returns NULL
unless a default value is provided.switch()
with FunctionsYou can call functions or expressions directly as case values:
operation <- "sum" result <- switch(operation, sum = sum(1:5), # sums 1 through 5 product = prod(1:5), # product of 1 through 5 mean = mean(1:5), NA # default return if no match ) print(result)
Output: 15
(because sum(1:5) = 15)
Use Case | Details |
---|---|
Character-based switch | Matches EXPR to case names |
Numeric-based switch | Uses position of cases to select |
Default case | Optional last argument if no match |
Case values | Can be expressions, function calls, or values |
Try writing a switch()
to simulate a simple calculator that takes an operation ("add", "subtract", "multiply", "divide") and two numbers, then performs the operation.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!