switch Statement
A switch statement in R allows a variable to be tested for equality against a list of values. Each value in a list is called a case, and the variable being switched on is checked for each case. R switch is almost the same as the if statement regarding working functionality. The basic syntax is
switch(expression, case 1, case 2, case 3, . . )
The expression values are tested against multiple cases (case1, case2, …, casen). The one-line syntax is,
An R Switch statement allows a default statement can also be added. The default statement will be executed, when the Expression value is not matching with any of the case statements. The following example is a simple command-line type calculator using R.
number1 <- 30 number2 <- 20 operator <- readline(prompt = "Enter any ARITHMETIC OPERATOR (+, -, *, ^, /, %/%, %%)!: ") switch(operator, "+" = print(paste("Addition (number1+number2) = ", number1 + number2)), "-" = print(paste("Subtraction (number1-number2) = ", number1 - number2)), "*" = print(paste("Multiplication (number1*number2) = ", number1 * number2)), "^" = print(paste("Exponent (number1^number2) = ", number1 ^ number2)), "/" = print(paste("Division (number1/number2) = ", number1 / number2)), "%/%" = print(paste("Integer Division (number1 %/% number2) = ", number1 %/% number2)), "%%" = print(paste("Division (number1 %% number2) = ", number1 %% number2)) )
From the above example, one can easily compute some basic computation on two numbers. The operation on these two numbers depends on the input is given to readline()
function and the expression in switch. The operator value from readline()
is matched with the options (cases) in the switch statement and results are displayed when matched.
Consider another example, for different probability, the area under the curve for a F-curve can be selected using the switch as given below.
# q contains the probability under the curve for a F-curve q <- c(0.25, 0.5, 0.75, 0.999) test = 3 v1 = 10 v2 = 20 switch(test, "1" = print (qf(q[1], df1=v1, df2=v2, lower.tail = T) ), "2" = print (qf(q[2], df1=v1, df2=v2, lower.tail = T) ), "3" = print (qf(q[3], df1=v1, df2=v2, lower.tail = T) ), "4" = print (qf(q[4], df1=v1, df2=v2, lower.tail = T) ) )
The code above will produce F-table values for different probability values.