How to do it…

Let's take a look at the following steps to learn about writing R using the switch function:

  1. The general structure of the switch function in R is as follows:
        switch(statement, list)
  1. Here, statement refers to the test condition and list refers to the list of tasks to complete. Here is the code to produce appropriate summary statistics as defined in the introduction section of this recipe:
        sym <- 1
switch(sym, function(x) c(mean=mean(x), std=sd(x)),function(x)
c(med=median(x), mad=mad(x)))
  1. Now, use the output of the switch function and calculate the summary statistics of any given numeric vector as follows:
        Fun1 <- switch(sym, function(x) c(mean=mean(x), std=sd(x)),
function(x) c(med=median(x), mad=mad(x)))
x <- c(13, 21, 19, 18, 21, 16, 21, 24, 17, 18, 12, 18, 29, 17,
18, 11, 13, 20, 25, 18, 15, 19, 21, 21, 7, 12, 23, 31, 16, 19,
23, 15, 25, 19, 15, 25, 25, 16, 29, 15, 26, 29, 23, 24, 20, 19,
14, 27, 22, 26)
Fun1(x)
mean std
19.800000 5.256677
  1. If the value of the sym variable is 2, then the corresponding output will be as follows:
        sym <- 2
Fun2 <- switch(sym, function(x) c(mean=mean(x), std=sd(x)),
function(x), c(med=median(x), mad=mad(x)))
Fun2(x)
med mad
19.0000 5.9304
..................Content has been hidden....................

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