Javatpoint Logo
Javatpoint Logo

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:

Flow Chart

R Switch Statement

Example 1

Output:

R Switch Statement

Example 2

Output:

R Switch Statement

Example 3

Output:

R Switch Statement

Example 4

Output:

R Switch Statement

Example 5

Output:

R Switch Statement
Next TopicR Next Statement





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA