R Switch Statement
A switch statement is a selection control mechanism that allows the value of an expression to change the control flow of program execution via map and search.
The switch statement is used in place of long if statements which compare a variable with several integral values. It is a multi-way branch statement which provides an easy way to dispatch execution for different parts of code. This code is based on the value of the expression.
This statement allows a variable to be tested for equality against a list of values. A switch statement is a little bit complicated. To understand it, we have some key points which are as follows:
There are basically two ways in which one of the cases is selected:
1) Based on Index
If the cases are values like a character vector, and the expression is evaluated to a number than the expression's result is used as an index to select the case.
2) Based on Matching Value
When the cases have both case value and output value like ["case_1"="value1"], then the expression value is matched against case values. If there is a match with the case, the corresponding value is the output.
The basic syntax of If-else statement is as follows: