R Tutorial



R SWITCH STATEMENT


The 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.

Basic Syntax

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.

Example 1: Using Character Cases

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 🍎

Example 2: Using Numeric Cases

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

Important Notes

  • If EXPR is a character, it matches the names of the cases.
  • If EXPR is numeric, it selects the case by its position (1-based).
  • If no match is found, switch() returns NULL unless a default value is provided.
  • Case values can be expressions or function calls, not just static values.

Example 3: Using switch() with Functions

You 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)

Summary

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

Practice Tip

Try writing a switch() to simulate a simple calculator that takes an operation ("add", "subtract", "multiply", "divide") and two numbers, then performs the operation.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review