R Switch
The switch() Function
In the If...Else chapter, you learned to use else if to test many conditions.
When all the conditions check the same variable, the code gets long:
Example
fruit <- "banana"
if (fruit == "apple") {
color <- "red"
} else if (fruit == "banana") {
color <- "yellow"
} else if (fruit == "grape") {
color <- "purple"
}
color
Try it Yourself »
The switch() function does the same thing in a shorter way. It compares a value with a list of names, and returns the value that belongs to the matching name:
Example
fruit <- "banana"
color <- switch(fruit,
"apple" = "red",
"banana" = "yellow",
"grape" = "purple"
)
color
Try it Yourself »
R compares fruit with each name. "banana" matches, so switch() returns "yellow", which is stored in the color variable.
Default Value
If no name matches, you can add a last value without a name. This is the default value:
Example
fruit <- "kiwi"
color <- switch(fruit,
"apple" = "red",
"banana" = "yellow",
"unknown color"
)
color
Try it Yourself »
Note: If no name matches and there is no default value, switch() returns NULL (nothing).
Same Result for Several Names
If a name has no value after the = sign, R uses the value of the next name.
Here, both "Sat" and "Sun" give "Weekend":
Example
day <- "Sun"
type <- switch(day,
"Sat" = ,
"Sun" = "Weekend",
"Weekday"
)
type
Try it Yourself »
Switch with Numbers
If the first argument is a number, switch() returns the value at that position:
Example
day <- 3
switch(day, "Mon", "Tue", "Wed", "Thu", "Fri")
Try it Yourself »
day is 3, so switch() returns the third value, "Wed".