switch statement in R
Switch case statements are a substitute for long if statements that compare a variable to several integral values. Switch case in R is a multiway branch statement. It allows a variable to be tested for equality against a list of values.
Switch statement follows the approach of mapping and searching over a list of values. If there is more than one match for a specific value, then the switch statement will return the first match found of the value matched with the expression.
Syntax:
switch(expression, case1, case2, case3....)
Here, the expression is matched with the list of values and the corresponding value is returned.
Important Points about Switch Case Statements:
Here, the expression is matched with the list of values and the corresponding value is returned.
Important Points about Switch Case Statements:
An expression type with character string always matched to the listed cases.
An expression which is not a character string then this exp is coerced to integer.
For multiple matches, the first match element will be used.
No default argument case is available there in R switch case.
An unnamed case can be used, if there is no matched case.
An expression which is not a character string then this exp is coerced to integer.
For multiple matches, the first match element will be used.
No default argument case is available there in R switch case.
An unnamed case can be used, if there is no matched case.
Example-1
x <- switch(
3,
"Susmitha",
"Nibu",
"Binu",
"Sumit"
)
print(x)
output:
[1] "Binu"
Example-2
ax= 1
bx = 2
y = switch(
ax+bx,
"Hello, Padma",
"Hello Arpita",
"Hello Binu",
"Hello Nishka"
)
print (y)
output:
[1] "Hello Binu"
y = "18"
x = switch(
y,
"9"="Hello Arpita",
"12"="Hello Vaishali",
"18"="Hello Nishka",
"21"="Hello Shubham"
)
print (x)
output:
[1]"Hello Nishka"
# Select first match and return its value
x <- "a"
v <- switch(x, "a"="apple", "a"="apricot", "a"="avocado")
print(v)
output:
[1] "apple"
Default case
In the case of no match, the unnamed element (if any) is returned. If there are more than one unnamed elements present, an error is raised.
# Select unnamed element in the case of no match
x <- "z"
v <- switch(x, "a"="apple", "b"="banana", "c"="cherry", "grapes")
print(v)
output:
[1]"grapes"
If the numeric value is out of range (greater than the number of choices), NULL is returned.
x <- 5
v <- switch(x, "apple", "banana", "cherry")
print(v)
output:
NULL
Comments
Post a Comment