R - Switch Statement

A 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 −

Flow Diagram

R switch statement

Example

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

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

[1] "third"