How SWITCH statement in R?

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:

  • 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:

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

Flow Chart

Example 1

x ← switch(
3,
“Shubham”,
“Nishka”,
“Gunjan”,
“Sumit”
)
print(x)

Output:

R Switch Statement

Example 2

ax= 1
bx = 2
y = switch(
ax+bx,
“Hello, Shubham”,
“Hello Arpita”,
“Hello Vaishali”,
“Hello Nishka”
)
print (y)

Output:

R Switch Statement

Example 3

y = “18”
x = switch(
y,
“9”=“Hello Arpita”,
“12”=“Hello Vaishali”,
“18”=“Hello Nishka”,
“21”=“Hello Shubham”
)

print (x)

Output:

R Switch Statement

Example 4

x= “2”
y=“1”
a = switch(
paste(x,y,sep=“”),
“9”=“Hello Arpita”,
“12”=“Hello Vaishali”,
“18”=“Hello Nishka”,
“21”=“Hello Shubham”
)

print (a)

Output:

R Switch Statement

Example 5

y = “18”
a=10
b=2
x = switch(
y,
“9”=cat(“Addition=”,a+b),
“12”=cat(“Subtraction =”,a-b),
“18”=cat("Division= ",a/b),
“21”=cat(“multiplication =”,a*b)
)

print (x)

Output:

R Switch Statement