Lesson contents

R — Multiway selection with switch

R's switch can select a named alternative for a character expression. Supply one unnamed fallback to handle an unexpected text value.

A simple example

Match one case

  1. Start with The name "two"
  2. Do this Match the named choice
  3. Result two
The name selects the matching branch of switch. The final unnamed choice handles other names.
Lesson.R
cat(switch("two", one = "one", two = "two", "other"))
Output
two
Advertisements

Route several event states to one action

Map queued and retry to the same pending action. A sent event is complete, and an unrecognized state is sent for review. An empty alternative falls through to the next one, allowing queued and retry to share the pending result. Use a single character value per call.

Queued or retry: Pending. Sent: Done. Other status: Review.
Route a parcel update

A parcel dashboard receives status updates. A queued parcel and a parcel awaiting retry both belong in the pending tray. Mark a sent parcel done and send unfamiliar statuses for review.

Run the example

Use R 4.x. Run these commands from the directory containing the example.

Rscript --vanilla Lesson.R
Lesson.R
route <- function(state) {
  switch(state, queued = , retry = "pending", sent = "done", "review")
}
states <- c("queued", "retry", "sent", "unknown")
writeLines(vapply(states, route, character(1)))
Output
pending
pending
done
review

Both pending states share one result. The other branches distinguish a known completion from a new or misspelled status.

Try it yourself

What should an unrecognized state such as paused produce?

Check your answer

It produces review. Add an explicit case when the application defines how to handle that state.

R Language Definition

Related tags

  • R
  • multiway selection
  • pattern matching
  • default case