R Switch Statement
The switch() function lets you branch on a single value and pick one of several outcomes without writing a long chain of else if statements.
Why switch()?
When you're testing one variable against many possible discrete values, a stack of else if blocks gets repetitive fast. switch() reads more like a lookup table: give it a value to match, list the possible cases, and it returns whichever case fits.
A Basic switch
day <- "Wed"
result <- switch(day,
Mon = "Start of the week",
Wed = "Midweek",
Fri = "Almost the weekend",
"Just another day"
)
print(result)Matching by Position vs by Name
switch() behaves differently depending on the type of the first argument. Give it a character value and it matches cases by name, as in the example above. Give it a numeric value instead, and it ignores the names entirely and picks the case at that position — 1 for the first, 2 for the second, and so on.
Numeric switch
rank <- 2
switch(rank,
"Gold",
"Silver",
"Bronze"
)Fall-Through Cases
Leaving a case's value empty makes it fall through to the next case that does have a value, which is a compact way to group several labels under one result.
Grouping Cases
day_type <- function(day) {
switch(day,
Mon = ,
Tue = ,
Wed = ,
Thu = ,
Fri = "Weekday",
Sat = ,
Sun = "Weekend"
)
}
day_type("Thu")
day_type("Sun")