Skip to content
AgileLogics
4 min read

switch and Multiple Choices

Prerequisites: Conditionals

When one value decides between several options, switch() is tidier than a long chain of if/else if.

switch with text

describe_day <- function(day) {
  switch(day,
    Saturday = ,
    Sunday = "Weekend!",
    Friday = "Almost weekend",
    "Weekday"
  )
}

describe_day("Sunday")
describe_day("Friday")
describe_day("Tuesday")
[1] "Weekend!"
[1] "Almost weekend"
[1] "Weekday"
  • Each named argument is an option; the value after = is the result.
  • An empty option (Saturday = ,) falls through to the next one, so Saturday and Sunday share a result.
  • The final unnamed value is the default.

(function defines a reusable function — covered in its own lesson shortly.)

Cutting numbers into ranges

For numeric ranges, cut() is the vectorized tool:

scores <- c(95, 84, 72, 55)
cut(scores,
    breaks = c(0, 70, 80, 90, 100),
    labels = c("F", "C", "B", "A"))
[1] A B C F
Levels: F C B A

cut returns a factor (a categorical value) — the Factors lesson explains the Levels: line. By default each range includes its upper boundary: (80, 90].

Common mistakes

  • Forgetting the default value in switch. Without it, an unmatched value returns NULL invisibly — easy to miss.

Practice

Write a function season(month) using switch that returns "winter", "spring", "summer", or "autumn" for month names such as "Jan" (Northern Hemisphere; Dec–Feb is winter).

Show solution
season <- function(month) {
  switch(month,
    Dec = , Jan = , Feb = "winter",
    Mar = , Apr = , May = "spring",
    Jun = , Jul = , Aug = "summer",
    Sep = , Oct = , Nov = "autumn",
    "unknown"
  )
}

season("Jul")
[1] "summer"