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 symmetric, and it will take a value 2 if the distribution is not symmetric. Then, based on this variable, the summary statistics will be calculated.

In this recipe, you will use the switch function to define another two different functions to calculate the appropriate summary statistics. The function for summary statistics will be as follows:

  1. function(x) c(mean = mean(x), std = sd(x))
  2. function(x) c(med= median(x), mad= mad(x))

Based on the value of the variable sym, the switch operator will return either of the preceding two functions for later use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset