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 382if (!is.String(x)) {x = as.character(x)class(x) = "String"}return(x)}is.String=function(x) return(class(x) == "String")(We write these functions as though they are “sourced” in from a file. The good way toorganize this would be to include all these new functions in a single file, as they are in afile in the <strong>Using</strong>R package.)Now when a generic function is called on an instance of this class, the function <strong>for</strong> theString class, if present, is used. For example, the String class should have some basicfunctions, such as length (), summary (), and print ()length.String = function(x,…) return(nchar(x))summary.String = function(x,…)return(table(strsplit(x,"")))print.String = function(x,…) cat(x,"\n")At this point we can see if it works as expected. For example:> bart=string("I will not skateboard in the halls")> bartI will not skateboard in the halls> length(bart)[1] 34> summary(bart)I a b d e h i k l n o r s t w6 1 3 1 1 2 2 2 1 4 2 2 1 2 3 1The summary () function splits the string into characters and then makes a table. Bymodifying the summary. string () function other summaries could be given.It would be nice to be able to access the letters in a String object as we do the elementsin a vector. First, let’s define a function slice() and then use this to define access via "[".To do so, slice () is made a “generic” function in order <strong>for</strong> method dispatch to work, andthen defined as desired:slice = function(x,index) UseMethod("slice")slice.String = function(x,index){tmp = unlist(strsplit(x,""))[index]return(string(paste(tmp,sep="",collapse="")))}To make slice () generic, we used UseMethod(). The definition of slice () uses strsplit ()to split the string into characters.To make the vector notation work on the String class, we overload the square-bracketmeaning by defining a function as follows:

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

Saved successfully!

Ooh no, something went wrong!