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
- Start with The name "two"
- Do this Match the named choice
- Result two
cat(switch("two", one = "one", two = "two", "other"))
two
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.
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
route <- function(state) {
switch(state, queued = , retry = "pending", sent = "done", "review")
}
states <- c("queued", "retry", "sent", "unknown")
writeLines(vapply(states, route, character(1)))
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.