switch statement in R Programming Language

Rumman Ansari   Software Engineer   2023-03-24   6434 Share
☰ Table of Contents

Table of Content:


switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax

The basic syntax for creating a switch statement in R is ?

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

The following rules apply to a switch statement ?

  • If the value of expression is not a character string it is coerced to integer.

  • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

  • If the value of the integer is between 1 and nargs()?1 (The max number of arguments)then the corresponding element of case condition is evaluated and the result returned.

  • If expression evaluates to a character string then that string is matched (exactly) to the names of the elements.

  • If there is more than one match, the first matching element is returned.

  • No Default argument is available.

  • In the case of no match, if there is a unnamed element of ... its value is returned. (If there is more than one such argument an error is returned.)

Flow Diagram

R switch statement

Example

x <- switch(
   3,
   "first",
   "second",
   "third",
   "fourth"
)
print(x)

When the above code is compiled and executed, it produces the following result ?

[1] "third"

This is a example of another way using function

Program


use.switch <- function(x)
{
  
  switch(x,
         "a" = "First",
         "b" = "Second",
         "c" = "Third",
         "z" = "Last",
         "others"
         )
  
}

Output


> use.switch("a")
[1] "First"
> use.switch("b")
[1] "Second"
> use.switch("r")
[1] "others"
> use.switch("z")
[1] "Last"
> use.switch(1)
[1] "First"
> use.switch(2)
[1] "Second"
> use.switch(3)
[1] "Third"
> use.switch(4)
[1] "Last"
> use.switch(5)
[1] "others"
> use.switch(6)
> is.null(use.switch(6))
[1] TRUE