R switch() Function

In this article, you will learn to use the switch() function in R programming with the help of examples.

The switch() function in R tests an expression against elements of a list. If the value evaluated from the expression matches an item from the list, the corresponding value is returned.

Syntax of the switch() Function

The syntax of the switch() function is:

switch (expression, list)

Here, expression is evaluated and based on this value, the corresponding item in the list is returned.

If the value evaluated from expression matches with more than one item of the list, the switch() function returns the first matched item.

Example: switch() function



[1] "green"
[1] "red"

In the above example, "red","green","blue" form a three item list.

The switch() function returns the corresponding item to the numeric value evaluated.

If the numeric value is out of range (greater than the number of items in the list or smaller than 1), then, NULL is returned.

x <- switch(4,"red","green","blue")
x <- switch(0,"red","green","blue")

Here, switch() is called with the first argument set to 4. It checks the value of the first argument and selects the corresponding value from the following arguments.

Since 4 matches the fourth position, the value "blue" is assigned to the variable x.

Example: switch() Function with as String Expression

The expression parameter used in the switch () function can be a string as well. In this case, the matching named item's value is returned.

switch("color", "color" = "red", "shape" = "square", "length" = 5)


[1] "red"

Here, "color" is a string which matches with the first item of the list. Hence, we are getting "red" as an output.

switch("length", "color" = "red", "shape" = "square", "length" = 5)


[1] 5

Similarly, "length" expression matches with the last item of the list. Hence, we are getting 5 as an output.

Also check this example to make a simple calculator in R using switch() function.

Did you find this article helpful?