Learn R Online

R switch () Function

In this tutorial you will learn about switch function in R programming with examples. You will learn how to use switch() with text and integer values. 

Switch statement is a selection structure which checks a value for equality against a list of values. Each value in the list is called case. In R the behavior of switch varies, for integers it returns the respective indexed item however in case of text it executes the matching case. 

Syntax of switch()

General syntax of switch is

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

If switch is used with a text value the syntax is 


            case 1: Code to be executed

            case 2: Code to be executed

            case 3: Code to be executed

            Execute this if no match


For an integer value the syntax is 

switch(integer, "value1", "value2", "value3", "value4")

Example: switch() function

# switch function in R

num <- '3'


       '1'  = print('One'),

       '2' = print('Two'),

       '3' = print('Three'),

       '4' = print('Four'),

       '5' = print('Five'),

       'You did not enter a number from 1 to 5:'


  > [1] "Three"

In this example num is a text variable. This variable is used in switch statement. In case if the value of num matches '1' then the block of code print('One') will be executed. If num matches '2' then the second line will be executed. In this case the value of num is '3' hence the third line will be executed or 'Three' will be printed as output. In the end a default case is given, which is executed if there is no match. 

Next example is for integer values. 

x <- 4

switch(x, "Apple", "Mango", "Guava", "Orange", "Pear")

>[1] "Orange"

In this example a numeric value is tested for a match against a list of values. If the value is entered is a number that item of list is returned. In case of a no match, NULL is returned.  

x <- 9

val <- switch(x, "Apple", "Mango", "Guava", "Orange", "Pear")


>[1] NULL