How to do it…

Let's take a look at the following two parts:

  • The repetition part: Let's take a look at the following steps to get a clear picture of the repetition part:
    1. Let’s first rewrite the fDescriptive function as follows:
             fDescriptive <- function(numVec, type = "classical"){
avg <- mean(numVec)
std <- sd(numVec)
med <- median(numVec)
medad <- mad(numVec)
out1 <- c(mean = avg, sd = std)
out2 <-c(median = med, mad = medad)
if(type== "classical")
return(out1)
else if (type == "robust")
return(out2)
}
  1. Now, using the function, you will calculate robust descriptive statistics for four columns of the iris dataset, a default dataset of flowers in R. This dataset has four numeric variables and one categorical variable:
             robustSummary <- apply(X = iris[,-5], MARGIN = 2, FUN =    
fDescriptive, type = "robust")
  • The recursion part: Let's take a look at the following steps to get a clear picture of the recursion part:
    1. The objective is to write a function to calculate the sum of a cubic series such as 1^3 + 2^3 + … +n^3 using the recursion technique. Let’s give the function name as cubicSum; you will use the cubicSum function within the body of this function as follows:
               cubicSum <- function(n){
if(n==0)
return(0)
else
return(n^3 + cubicSum(n-1))
}
  1. The use of the function is as follows:
               cubicSum(n = 3)
..................Content has been hidden....................

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