Writing a function using the switch operator
While writing a program, you might encounter a situation where you have to pick an item from a list based on a certain value of a test condition. The switch
operator or the switch
function in R is very handy in this type of situation. In this recipe, you will learn how to write R using the switch
function.
Getting ready
Suppose you are working on a problem where you have a series of numeric variables and your task is to produce the most appropriate summary statistics for all of them. If the distribution is symmetric, then you will produce the mean and standard deviation. However, if the distribution is not symmetric, then your task is to calculate the median and MAD. In this type of situation, the use of the switch
operator comes into play. To execute the whole task, there is a part where you will test whether the distribution is symmetric or not. Let’s say you have defined a variable sym
. This variable will take a value 1
if the distribution is...