How it works...

In step 1, we create a generic function called plot.SimpleGenome(). The special naming convention here marks this out as a member of the group of generic plot functions specific to objects of the SimpleGenome class. The convention is method.class. This is all we need for the generic plot method to work.

In step 2, we actually create a SimpleGenome object as we did in the Creating simple S3 objects to simplify code recipe in this chapter (you'll need to make sure that recipe's step 1 was executed in the current session for this step to work), and then call plot() on it. The plot method looks up the generic function for the SimpleGenome objects and runs that object, giving us the barplot we expect, as shown in the following diagram: 

With step 3, we take things a little deeper. In this step, we want to use a method name (genome_lengths) that doesn't already exist (you can use the methods() function to see those that exist), so we must first create the method group. We do that by creating a function that calls the UseMethod() function, with the name of the method we want to create as the enclosing function name and the first argument. With that done, we can create the generic function for our SimpleGenome class and use it on our objects by simply calling genomeLength(). As our generic function simply adds up the chromosome_lengths vector, we get a result like this:

> genomeLength(athal)
[1] 134634692

Step 4 shows the mechanics of the class lookup system. We first make a copy of the iris data and then use the summary() method on it, giving the standard result for a dataframe:

> summary(some_data) 
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 setosa :50
1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 versicolor:50

Next, we use the class() function, in step 4, to add a new class to the some_data object. Note we add it as the first element of the vector. We can see that the data.frame class is still there but is later in the order than the one we added:

> class(some_data) 
[1] "my_new_class" "data.frame"

Then, in step 5, we create a generic summary() function for my_new_class so that it returns a very different type of summary. We see that when we call it:

> summary(some_data) 
[1] "object contains 5 columns of classes:numeric,numeric,numeric,numeric,factor"

The point to note is that, although the object had more than one class, by default, the first generic function that matches a class is chosen. Try switching the order of the class attribute if you'd like to test this out.

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

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