In this article, with the help of examples, the use of the switch function in R language reviewed in armancomputer scientific magazine which has an important role to program multiple conditions. As you know, R is a computational programming specially design for statistics.
The switch function in R evaluates an expression against the elements of a list and matches the evaluated value of the item expression in the list. The result of this function will be one of the list values. The command form of the switch function is as follows.
1 |
switch (expression, list) |
Here the expression is evaluated and based on it, an option is selected from the List and returned by the function. Note that the expression must contain integer values. If the expression value is greater than the number of list elements, the switch function returns NULL value. In order to clarify the issue, we will mention some examples.
Example 1:
1 2 3 4 |
switch(2,"red","green","blue") "green" switch(1,"red","green","blue") "red" |
As you can see, according to the value introduced as the first parameter of this function, one of the list options is displayed by the function.
Note: If a value in the list is duplicated, the function returns only the first value.
Example 2:
1 2 3 4 5 6 |
x <- switch(4,"red","green","blue") x NULL x <- switch(0,"red","green","blue") x NULL |
It is also clear here that the value of the first parameter in the above command is outside the scope of the introduced list options, as a result of the execution of the switch function, the same value will be NULL. You can even use text comparison strings for the switch function. Pay attention to the following example.
Example 3
1 2 |
switch("color", "color" = "red", "shape" = "square", "length" = 5) "red" |
The switch function, since color is a text value for the parameter, will search it in the list and show the expression after equals as the result of the function. Also, in the following command, the output will be equal to 5.
1 2 |
switch("length", "color" = "red", "shape" = "square", "length" = 5) 5 |
As you see, text expressions can also be used in switch function in R language. It is clear that the switch function in R language has various uses, which we will discuss in other articles of ArmanComputer magazine, and we will get to know such uses through various examples.
Thank you for sharing this information! If you need some details about Engineering than have a look here Webemail24