How it works…

The first phase of defining a generic function is defining a function and mentioning the use method for that function. The function robSum() has use method robSum; in other words, using this name, you have to call this generic function.

Every generic function usually has a default method where the default task has been defined. In this example, the default method is just printing a line of text This is a generic function for the object class robustSummary. Whenever the default method of this robSum() generic function call or the input object's class is not robustSummary, it will print this default line.

The final step is to define the method for the targeted class. In this example, the class name is robustSummary. The method has been defined by the robSum.robustSummary() function. Whenever the input object has the class robustSummary, it will print the median, MAD, first quartile, and third quartile. This function will act like an alternative generic implementation of the print() function with the robustSummary method.

Now, let’s create an object with the "robustSummary" class and call the newly created generic function and methods, as shown in the following code:

        > set.seed(123) # to make the result reproducible 
> newX <- rnorm(50) # generating 50 ranodm numbers from standard
normal distribution
> robSum.default(obj = newX)
This is a generic function for the object class 'robustSummary'

> class(newX) <- "robustSummary"
> robSum.default(obj = newX)
This is a generic function for the object class 'robustSummary'

> robSum.robustSummary(obj = newX)
Median -0.07264039
Median Absolute Deviation (MAD) 0.9164537
First Quartile (Q1) -0.559317
Third Quartile (Q3) 0.698177
..................Content has been hidden....................

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