R switch statement

Switch statement is a control statement that allows us to choose only one choice among the many given choices. If we are checking on the value of a single variable in if…else…if , it is better to use switch statement. The switch statement is often faster than nested if…else.

Syntax:

switch(var, value1={expression1} value2={expression2} )

var1 <- 'R' #Define variable

switch(var1, R={ # case ‘R’ here… print(‘R’) }, Python={ # case ‘Python’ here… print(‘Python’) }, { print(‘default’) } )


output:

[1] “R”

Powered by WordPress