In this tutorial you will learn about the R Switch Statement and its application with practical example.
R Switch Statement
In R, switch statement evaluates equality of an variable/expression value against multiple case values in order to identify the block of code to be executed.
Syntax:-
1 |
switch(expression, case1, case2, case3...., caseN) |
Here, expression values is tested against multiple case values (case1, case2, case3…., caseN)
The following rules apply to a switch statement –
- If the expression value is not a character string it is coerced to integer.
- In switch you are allowed to have any number of case statements.
- If there is more than one match, the first matching element is returned.
- There is no default value/case is available.
- If no match found and there is an unnamed element, its value is returned.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
dayOfWeek <- 5 dow <- switch( dayOfWeek , "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ) print("W3Adda - R Switch Statement") print(dow) |
Output:-