switch() function in R

switch() function in R is a built-in function used to test a variable for equality against a list of cases. The switch() function behaves differently when integer and character string expressions are used. When used with an integer expression, it returns the indexed item. However, when used with a character string, it checks for the matching case in the list of cases.

This guide will explain how to use the switch() function in R.

Syntax

switch(expression, case1, case2, case3,....)

Arguments

  • expression = the expression to be evaluated. It can be an integer or a character string
  • case1, case2, case3…. = a list of values.

Example 1: switch() function with Integer Expression

In this example, we use an integer as an expression to return the indexed item from the list of cases.

#switch function in R
switch(3,'Superman','Aquaman','Batman','Spiderman','Ironman')

Output

[1] "Batman"

Example 2: switch() function with Character String Expression

In this example, we use a character string as an expression that will return the matched case from the list of cases.

#switch function in R
switch('Metal','Strength'='Superman','Water'='Aquaman','Martial Arts'='Batman','Web'='Spiderman','Metal'='Ironman')

Output

[1] "Ironman"

Example 3: switch() function with Multiple Matches

If there is more than one expression match in the list of cases, then the switch() function will return the first matched value.

switch('Bruce','Clark'='Superman','Bruce'='Hulk','Bruce'='Batman','Peter'='Spiderman','Tony'='Ironman')

Output

[1] "Hulk"

Leave a Comment