R Switch Statement

The switch statement selects one block of code from several options based on the exact value of an expression. Use it when you have a fixed set of known choices. It is cleaner and more readable than a long else-if ladder when each branch corresponds to a specific, exact value.

Syntax

switch(expression,
  "value1" = { code block 1 },
  "value2" = { code block 2 },
  "value3" = { code block 3 },
  { default code block }      # optional
)

How switch Works

expression = "mango"

     switch()
         │
         ├── "apple"  ✗ (no match)
         ├── "mango"  ✓ MATCH → run this block
         ├── "banana" (skipped)
         └── default  (skipped)

Basic Example

day <- "Wednesday"

result <- switch(day,
  "Monday"    = "Start of work week",
  "Wednesday" = "Mid week",
  "Friday"    = "End of work week",
  "Weekend day"    # default
)

cat(result, "\n")

Output:

Mid week

Practical Example: Currency Converter

currency <- "EUR"
amount   <- 100

rate <- switch(currency,
  "USD" = 83.5,
  "EUR" = 91.2,
  "GBP" = 106.8,
  "JPY" = 0.56,
  stop("Unknown currency")   # error for unknown values
)

inr <- amount * rate
cat(amount, currency, "=", inr, "INR\n")

Output:

100 EUR = 9120 INR

Switch With Numeric Index

When the expression is a number, switch selects by position:

choice <- 2

result <- switch(choice,
  "First option",    # choice = 1
  "Second option",   # choice = 2
  "Third option"     # choice = 3
)

cat(result, "\n")

Output:

Second option

Fall-Through: Multiple Values, Same Action

Leave a case empty to fall through to the next non-empty case:

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

cat(day_type("Tuesday"), "\n")   # Weekday
cat(day_type("Sunday"), "\n")    # Weekend

switch vs else-if: When to Use Which

Use switch when:                   Use else-if when:
──────────────────────────────────────────────────────────────
Exact match to a set of values     Range checks (x > 100)
Known, finite set of choices       Multiple conditions combined
Cleaner code over many exact       Conditions depend on different
options (5+ branches)              variables

The switch statement shines when you route program logic based on category labels, menu selections, or type codes. It is shorter and easier to extend than a chain of else-if statements when all branches test the same variable for exact equality.

Leave a Comment

Your email address will not be published. Required fields are marked *