R: Switch Statement

Switch Statements is used to test the equality against a list of values each values is known as a case and the variable being switched on is checked for each case. It is used in place of long if statement which compares a variable with several values.

Switch case in R is a multi-way branch statement which provide easy ways to execute different parts of code. Its code is based on the value of the expression.

It is a selection control mechanism which allows the value of an expression to change the control flow of program execution. It follows the approach of mapping and searching over a list of values.

Some important points:

  • In case if there is more than one match then the first match element is used.
  • Unnamed case is used if no matched case is found.
  • No default argument case is available¬†

Syntax

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

Example

x<-2 
y<-switch(
     x,
     "Monday",
     "Tuesday",
     "Wednesday",
     "Thursday",
     "Friday"
 )

print(y)

Output: [1] "Tuesday"