R switch() Function

The nested if…else statement is especially useful when you want to execute a certain block of code when a condition is met.

However, if you want to select values based only on a condition, you have a better option: Use the switch() function.

Syntax

Here’s the syntax of the switch() function:

r switch statement syntax

switch() with String Expression

If the expression is a character string, switch() will return the value based on the name of the element.

Example: Select elements by name and return their value

> x <- "a"
> v <- switch(x, "a"="apple", "b"="banana", "c"="cherry")
> v
[1] "apple"
> 
> x <- "c"
> v <- switch(x, "a"="apple", "b"="banana", "c"="cherry")
> v
[1] "cherry"

In case of multiple matches, the value of first matching element is returned.

Example: Select first match and return its value

> x <- "a"
> v <- switch(x, "a"="apple", "a"="apricot", "a"="avocado")
> v
[1] "apple"

Default case

In the case of no match, the unnamed element (if any) is returned.

If there are more than one unnamed elements present, an error is raised.

Example: Select unnamed element in the case of no match

> x <- "z"
> v <- switch(x, "a"="apple", "b"="banana", "c"="cherry", "grapes")
> v
[1] "grapes"

switch() with Numeric Expression

The numeric version of switch() works in a slightly different way.

Instead of using names, the return value is determined purely with positional matching (Index).

Example: Select elements by position and return their value

> x <- 1
> v <- switch(x, "apple", "banana", "cherry")
> v
[1] "apple"

> x <- 3
> v <- switch(x, "apple", "banana", "cherry")
> v
[1] "cherry"

If the numeric value is out of range (greater than the number of choices), NULL is returned.

Example: Returns NULL if index is out of range

> x <- 5
> v <- switch(x, "apple", "banana", "cherry")
> v
NULL