Learn R Programming  /  Control Flow  /  switch()

switch()

switch() branches based on the exact value of a single expression โ€” a cleaner alternative to a long chain of if...else if statements when checking one variable against several fixed options.

Basic switch()

R Code
day <- "Tue"

result <- switch(day,
  "Mon" = "Start of week",
  "Tue" = "Second day",
  "Fri" = "Almost weekend",
  "Unknown day"   # default, no matching name
)
result
Output
[1] "Second day"

Fall-Through Cases

Leaving a case empty makes it fall through to the next matching case โ€” handy for grouping several inputs under one result.

R Code
day <- "Sat"

type <- switch(day,
  "Sat" = ,
  "Sun" = "Weekend",
  "Weekday"
)
type
Output
[1] "Weekend"

Numeric switch()

With a numeric first argument, switch() picks the option at that position instead of matching by name.

R Code
n <- 2
switch(n, "first", "second", "third")
Output
[1] "second"
⚠ Common Mistake
If no case matches and there is no default value, switch() returns NULL invisibly - which can silently break code further down the line. Always add a default (an unnamed last option) unless you are certain every possible value is covered.

Advanced: switch() Inside a Function

🚀 Advanced Example
switch() is often used inside a function to select which calculation to run, based on a mode argument.
R Code
convert_temp <- function(value, to) {
  switch(to,
    fahrenheit = value * 9/5 + 32,
    kelvin     = value + 273.15,
    stop("Unknown target unit")
  )
}

convert_temp(25, "fahrenheit")
convert_temp(25, "kelvin")
Output
[1] 77
[1] 298.15

Key Points

  • switch() matches the exact value of one expression against a set of named cases.
  • An empty case falls through to the next case below it.
  • Always include a default/unnamed case, or a missing match silently returns NULL.