How it works...

Step 1 is where all the work happens. This is all we need to create an S3 object. As you can see, it is very lightweight code. We simply create a function that generates and returns a data structure. Our class is supposed to represent a simplistic genome and we want it to hold some basic information about a genome. The SimpleGenome() function is our constructor of objects. The genome list created by SimpleGenome is the data structure that makes up the body of the eventual object. The members of this list are the slots of the object, so we create members called chromosome_count and chromosome_length to represent some features of the genome. With that done, we carry out the important step—we append the class name (SimpleGenome) to the class attribute of the genome list. It is this that makes R recognize the object as being of the SimpleGenome class. We can now return the created S3 object.

In step 2, we simply use the constructor to make instances of the class. Inspecting the resulting objects looks like this:

> ecoli 
$chromosome_count
[1] 1
$chromosome_lengths
[1] 4600000
attr(,"class")
[1] "list" "SimpleGenome"

> bakers_yeast
$chromosome_count
[1] 1
$chromosome_lengths
[1] 12100000
attr(,"class")
[1] "list" "SimpleGenome"

We can see the object slots, the differences in the objects, and the class containing the new SimpleGenome object. This is how we create an S3 object; it's a simple but effective way of doing things. The advantages over just creating a normal data structure such as a list are not immediately obvious, but when we look at how to create methods in the next recipe the reasons will be clearer.

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

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