A switch statement is a selection control mechanism which is used to choose one of the statements to execute from the multiple available statements, relative to the true condition. It is a conditional statement or a multi-way branch statement in R that can be used to avoid. Some of the important considerations related to the switch statement in R are:
- For character string as a condition for switch statement, the string is matched to the available cases.
- In cases of multiple matches, the first match element is executed.
- There is no default value to execute.
Methods:
The switch statement in R can use either of the two available methods to select a case to execute.
The result of the expression is used as an index to decide the case when values like a character vector are used as cases, and the expression is evaluated to a number.
The expression value is matched against case values if the cases have both case value and output value. For example: [“case1″=”value”]. The corresponding value of the matched case is displayed as the output.
Syntax:
switch(expression, case1, case2, case3....) |
switch(expression, case1, case2, case3....)
Example 1:
var <- switch(
4,
"APPLE",
"BOY",
"CAT",
"DOG",
"ELEPHANT"
)
print(var) |
var <- switch(
4,
"APPLE",
"BOY",
"CAT",
"DOG",
"ELEPHANT"
)
print(var)
Output:
Example 2:
N1 = 2
N2 = 3
var = switch(
N1+N2,
"APPLE",
"BOY",
"CAT",
"DOG",
"ELEPHANT"
)
print (var) |
N1 = 2
N2 = 3
var = switch(
N1+N2,
"APPLE",
"BOY",
"CAT",
"DOG",
"ELEPHANT"
)
print (var)
Output:
Example 3:
Alpha = "C"
var = switch(
Alpha,
"A"="APPLE",
"B"="BOY",
"C"="CAT",
"D"="DOG",
"E"="ELEPHANT"
)
print (var) |
Alpha = "C"
var = switch(
Alpha,
"A"="APPLE",
"B"="BOY",
"C"="CAT",
"D"="DOG",
"E"="ELEPHANT"
)
print (var)
Output:
Example 4:
N1 = "3"
N2 ="3"
var = switch(
paste(N1,N2,sep=""),
"9"="APPLE",
"18"="BOY",
"22"="CAT",
"33"="DOG",
"21"="ELEPHANT"
)
print (var) |
N1 = "3"
N2 ="3"
var = switch(
paste(N1,N2,sep=""),
"9"="APPLE",
"18"="BOY",
"22"="CAT",
"33"="DOG",
"21"="ELEPHANT"
)
print (var)
Output:
Example 5:
N1 = "Y"
N2 ="Z"
var = switch(
paste(N1,N2,sep=""),
"XY"="APPLE",
"YZ"="BOY",
"PQ"="CAT",
"RS"="DOG",
"AB"="ELEPHANT"
)
print (var) |
N1 = "Y"
N2 ="Z"
var = switch(
paste(N1,N2,sep=""),
"XY"="APPLE",
"YZ"="BOY",
"PQ"="CAT",
"RS"="DOG",
"AB"="ELEPHANT"
)
print (var)
Output:
Example 6:
choice = "SUB"
N1 = 100
N2 = 88
Calculator = switch(
choice,
"ADD"=cat("Addition =",N1+N2,"\n"),
"SUB"=cat("Subtraction =",N1-N2,"\n"),
"DIV"=cat("Division =",N1/N2,"\n"),
"MUL"=cat("Product =",N1*N2,"\n")
)
print(Calculator) |
choice = "SUB"
N1 = 100
N2 = 88
Calculator = switch(
choice,
"ADD"=cat("Addition =",N1+N2,"\n"),
"SUB"=cat("Subtraction =",N1-N2,"\n"),
"DIV"=cat("Division =",N1/N2,"\n"),
"MUL"=cat("Product =",N1*N2,"\n")
)
print(Calculator)
Output: