Switch Statement in R Language

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. To understand it, we have some key points which are as follows:

  • If expression type is a character string, the string is matched to the listed cases.
  • If there is more than one match, the first match element is used.
  • No default case is available.
  • If no case is matched, an unnamed case is used.

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:

The basic syntax of If-else statement is as follows:

switch(expression, case1, case2, case3….)  

Let’s Work on few Examples:

in this example, 3 is expression, and “Swaroopa”, “Jo”, “sri”, “Subha” are switch Cases, The out Put value of X is Sri, because the expression is 3 and the Index of three is sri