What is the use of the switch() function in R?

The switch() function in R is a multiway branch control statement that evaluates an expression against items of a list. It has the following syntax:

switch(expression, case_1, case_2, case_3....)Powered By 

The expression passed to the switch() function can evaluate to either a number or a character string, and depending on this, the function behavior is different.

1. If the expression evaluates to a number, the switch() function returns the item from the list based on positional matching (i.e., its index is equal to the number the expression evaluates to). If the number is greater than the number of items in the list, the switch() function returns NULL. For example:

switch(2, "circle", "triangle", "square")Powered By 

Output:

"triangle"Powered By 

2. If the expression evaluates to a character string, the switch() function returns the value based on its name:

switch("red", "green"="apple", "orange"="carot", "red"="tomato", "yellow"="lemon")Powered By 

Output:

"tomato"Powered By 

If there are multiple matches, the first matched value is returned. It’s also possible to add an unnamed item as the last argument of the switch() function that will be a default fallback option in the case of no matches. If this default option isn’t set, and if there are no matches, the function returns NULL.

The switch() function is an efficient alternative to long if-else statements since it makes the code less repetitive and more readable. Typically, it’s used for evaluating a single expression. We can still write more complex nested switch constructs for evaluating multiple expressions. However, in this form, the switch() function quickly becomes hard to read and hence loses its main advantage over if-else constructs.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *