R Switch | R Switch Functions - r - learn r - r programming
- In R, switch statement evaluates equality of an variable or expression against multiple case values in order to evaluate the block of code to be executed.
- The switch takes an expression and returns a value in a list built on the value of the expression which depends on the data type of the expression.
- In switch expression values is tested against multiple case values (case1, case2, case3..., caseN)
Syntax
Syntax Explanation:
- statement:The statement is assessed based on this value and the result.
- list: The equivalent item in the list is returned, if the value is a number between 1 and the length of list. If the value is too large or too small, then NULL is returned.
Read Also
Sample Code
Code Explanation
- There are three of list items "Mango", "Apple", "Guava". The switch() function returns the corresponding item to the numeric value 3.
- The switch() function returns the corresponding item to the numeric value 1 is then assessed.
- Next we create a three of list items "Mango", "Apple", "Guava". Here the switch() function returns the corresponding item to the numeric value 0 and is evaluated.
- By the same way, the switch() function returns the corresponding item to the numeric value 4 is evaluated.
- Here, represented a “color” string which means the matching named item's value is returned.
- This statement can be denoted as a “price” string that means the matching named item's value is displayed.
Output
- In this output "Guava","Mango" is a list of items. Therefore, the switch() function returns the selected numeric values 3 & 1 evaluated.
- Here, the numeric value is out of range, which means 4 is greater than the number of items in the list and 0 is smaller than 1, then, output prints NULL as a return value.
- In this statement can be represented as "color" and “price” strings, which means the matching named item's “yellow” and “50” values are returned as output.