R Switch Statement

It is an alternate way to a nested if…else statement. A switch statement permits an expression to be tested against a list of case values. In short, we can say that a switch statement is used to compare an expression to known values or number of cases.


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

First of all, it will enter the switch case statement which has an expression. Next, it will go to the case1 condition, checks the value passed to the condition. If it is true, the block of statements will execute. After that, it will break from the first switch case.

In case it is false, then it will go to the next case i.e. case2. If the case2 condition is true, it will execute the statement and then break from the case, else it will again switch to the next case.

In case of no match or there is some wrong input from the user, then it will go to the default case where it will print your statement of the default block.

Flow Chart:

R Switch Statement                      


y = 3
x = switch(
print (x)


[1] "Nidhi"