10.07.2015 Views

Using R for Introductory Statistics : John Verzani

Using R for Introductory Statistics : John Verzani

Using R for Introductory Statistics : John Verzani

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Appendix E 389Now, instances of the Sentence class inherit all the methods of the String class.> flanders = Sentence$new("the Flanders are Ned, Maude,Todd, and Rod")> flandersthe Flanders are Ned, Maude, Todd, and RodThis shows that the print () method was inherited. We can add more methods to theSentence class that are specific to that class. For example, we might want to ensure thatour sentences are punctuated with a capital letter <strong>for</strong> the first letter, and a period <strong>for</strong> thelast character.Sentence$defineMethod("punctuate",function() {## add a period, and capitalize the first letterchars = split("")chars[1] = toupper(chars[1])if(chars[(length)(chars)] != ".")chars[(length)(chars)+1]="."set.string(paste(chars,sep="",collapse=""))})We define punctuate () using def ineMethod(). The split () method uses the methoddefined <strong>for</strong> the String class, whereas the length () functions are <strong>for</strong> the length of acharacter vector. OOP would try to use the length () method we defined, so we need toplace the function in parentheses to use the one we want. Warning messages will remindus if we get this wrong.We can now punctuate our sentences:> flanders$punctuate()> flandersThe Flanders are Ned, Maude, Todd, and Rod.Inheritance with S4 methods is very similar. Again, the classes that the new class extends(the superclasses) are specified at the time a new class is made. For example:setClass("Sentence",contains=c("String"))The argument is contains= and not extends=.New instances are made with new() as be<strong>for</strong>e:sentence = function(x) {new("Sentence",string=x)}Methods <strong>for</strong> the new class are added in a similar manner:setGeneric("punctuate", function(object)standardGeneric("punctuate"))

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!