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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Appendix E 385})We need to use the argument x in length() and object in summary() to match their <strong>for</strong>malarguments (signature). The signature of a function can be found from its help page (e.g.,?summary), or with the function args() (e.g., args (summary)).New methods can be created as well. For example, to create a slice () method and the"[" syntax, we first create a generic function slice (), adapt it to the String class, and thenlink "[" to this.setGeneric("slice", function(object,index)standardGeneric("slice"))This sets up slice () as a generic function <strong>for</strong> which method dispatch will apply. Thedefinition of the function sets up the signature of the slice () function, namely an objectand an index. The definition of slice() <strong>for</strong> the String class issetMethod("slice","String",function(object,index) {tmp =paste(unlist(strsplit(object@string,"")[index],sep="",collapse="")return(string(tmp))})To define the "[" method, we again use setMethod(). It does not need to be made generic,but the signature must match.setMethod("[","String".function(x,i,j,…,drop)slice(x,i))There is a long list of <strong>for</strong>mal arguments. The "[" method works <strong>for</strong> vectors, data frames,arrays, and now strings, so it needs to have lots of flexibility in how it is called. We havelittle flexibility in how a new method is defined, though: at the minimum, we mustinclude all the arguments given.We can try this out:> pets=string("Snowball, Santa’s little helper")> pets[−1]nowball, Santa’s little helper> pets[length(pets)]rThe OOP packageFor those used to programming in an OOP language, the S3 and S4 methods might becalled “object oriented,” but they don’t look object oriented. Usually, the syntax <strong>for</strong>calling a method is object-separator-methodname, such as $object->print () in PERL orobject .print () in Ruby, C++, and Java. The separators -> and . are not well suited <strong>for</strong> R,

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

Saved successfully!

Ooh no, something went wrong!