01 / 20

The R switch()
Function

Learn how to route your code down different paths based on a single value: cleaner, faster, and more readable than chained if/else blocks.

R Programming

What Is switch()?

switch() is a built-in R function that takes a single expression (usually a character string) and compares it against a list of named cases. When it finds a match, it returns the value associated with that case.

Instead of writing long chains of if ... else if ... else, switch() lets you handle multiple known options in a single, compact expression.

Why Use switch()?

Readability
Each case is on its own line with a clear label: easy to scan and understand at a glance.
Conciseness
Replace 10+ lines of if/else chains with a single, compact switch() call.
Maintainability
Adding a new case is as simple as adding one more named argument: no restructuring needed.

The Routing Metaphor

Input: "blue" switch() "red" "#FF0000" "blue" "#0000FF" "green" "#00FF00" One input → one matching output

The value of the expression (here, a color name) determines which branch runs. Only the matching case returns its result: all others are skipped.

Core Syntax

switch(EXPR,
  "case1" = result1,
  "case2" = result2,
  "case3" = result3,
  default_result  # optional fallback
)
1
EXPR: the expression to evaluate (typically a character string or variable).
2
Named cases: each case is a name = value pair. R matches EXPR against the names.
3
Default: an unnamed argument at the end acts as a fallback if nothing matches.

How R Evaluates switch()

1. Evaluate EXPR 2. Compare to case names Match? Yes Return No Try next case If no case matches and no default → returns NULL

switch() vs if/else

switch() if/else chain
Best for One value, many known options Complex logical conditions
Input type Character string (or integer) Any logical expression
Readability High: flat list of cases Moderate: nested blocks
Adding cases Add one argument Add another else if block
Default Unnamed last argument Final else block
Range checks Not supported Supported

How to Apply switch()

1
Identify the routing variable: what single value determines the branch? (e.g., a user choice, a category name)
2
List all valid cases: write out every known option as a named argument inside switch().
3
Assign results: for each case name, provide the value or expression to return.
4
Add a default (optional): include an unnamed final argument to handle unexpected inputs gracefully.
5
Test edge cases: what happens if the input is misspelled or missing? Does NULL cause problems downstream?

Example 1: Day Type

day <- "Saturday"

day_type <- switch(day,
  "Monday"    = "Weekday",
  "Tuesday"   = "Weekday",
  "Wednesday" = "Weekday",
  "Thursday"  = "Weekday",
  "Friday"    = "Weekday",
  "Saturday"  = "Weekend",
  "Sunday"    = "Weekend"
)

Example 2: Fall-Through Cases

When multiple cases should return the same value, leave the earlier ones empty: R falls through to the next non-empty result.

day <- "Tuesday"

day_type <- switch(day,
  "Monday" = ,
  "Tuesday" = ,
  "Wednesday" = ,
  "Thursday" = ,
  "Friday" = "Weekday",
  "Saturday" = ,
  "Sunday" = "Weekend"
)

Example 3: Using a Default

fruit <- "mango"

price <- switch(fruit,
  "apple"  = 1.20,
  "banana" = 0.50,
  "cherry" = 3.00,
  0.00  # default: unknown fruit
)

Example 4: switch() Inside a Function

calculate <- function(op, a, b) {
  switch(op,
    "add"      = a + b,
    "subtract" = a - b,
    "multiply" = a * b,
    "divide"   = a / b,
    stop("Unknown operation: ", op)
  )
}

Anatomy of a switch() Call

switch( animal , "cat" = "meow" , "dog" = "woof" , "cow" = "moo" , "unknown" ) EXPR: the routing variable Case name (must match) Return value for match Default: no name needed If animal = "dog" → switch() returns "woof" If animal = "fish" → returns "unknown" (the default)

Key Rules to Remember

Character input
switch() works best with character strings. Integer input uses positional matching (rare and less readable).
Exact match only
Case names must match exactly: "Cat" and "cat" are different. No pattern matching or ranges.
Returns a value
switch() is an expression: it returns the matched result. You can assign it directly to a variable.

Common Mistakes

✕ Forgetting the default
Without a default, unmatched input returns NULL silently. This can cause hard-to-find bugs later in your code.
✕ Case sensitivity
Passing "Apple" when cases are "apple" won't match. Use tolower() to normalize input before switching.
✕ Using non-character EXPR
Passing a numeric or logical value triggers positional matching, not name matching: this is rarely what you want.

Summary Cheat Sheet

Feature Details
Purpose Route code by matching one value to named cases
Syntax switch(EXPR, "case" = value, ...)
Input type Character string (preferred) or integer
Match type Exact match only (case-sensitive)
Fall-through Only with empty cases (name = ,)
Default Unnamed last argument (or use stop())
No match + no default Returns NULL (invisible)

Question 1 of 5

What does switch() do when the input expression does not match any named case and no default is provided?

Question 2 of 5

What value is stored in result?

Question 3 of 5

Which of the following is NOT a good use case for switch()?

Question 4 of 5

In R's switch(), how do you make multiple case names return the same value?

Question 5 of 5

What does get_sound("Cat") return?