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 390setMethod("punctuate","Sentence",function(object) {## add a period, and capitalize the first letterchars = split(object,"")chars[1] = toupper(chars[1])if(chars[length(chars)] != ".")chars[length(chars)+1] = "."return(sentence(paste(chars,sep="",collapse="")))})In this case, the object is not modified. Rather, a new sentence is returned. Again split isused from the definition in String. Here the function length() is correctly dispatched, andthere is no need to include it in parentheses.For more in<strong>for</strong>mation on S4 classes, the help page ?Methods gives pointers and linksto other help pages. There is an in<strong>for</strong>mative article on S4 classes in Volume 3/1 (June2003) of R News (http://www.r-project.org/). For the OOP package the help page ?defineClass provides useful in<strong>for</strong>mation and links to the rest of the documentation. An outof-date,but still in<strong>for</strong>mative description by the OOP authors is contained in the Volume1/3 (September 2001) of R News.ProblemsE.1 Write your own sample standard deviation function, std, using the sample variance<strong>for</strong>mulaE.2 Write two functions push () and pop (). The first should take a vector and anargument and add the argument to the vector to make it the last value of the vector. Thefunction pop () should return the last value. How might you modify pop to return thevalue and the shortened vector? How might you change pop and push when x is an emptyvector?E.3 Write a short function to plot a simple lag plot (cf. ?lag.plot in the ts package).That is, <strong>for</strong> a vector x of length n, make a scatterplot of x [-n] against x[−1]. Apply thefunction to random data (rnorm(100)) and regular data (sin(1:100)).E.4 Write a function to find a confidence interval based on the t-statistic <strong>for</strong>summarized data. That is, the input should be S, n, and a confidence level; the outputshould be an interval.E.5 Newton’s method is a simple algorithm to find the zeroes of a function. Forexample, to find the zeroes of f(x)=x 2 −sin(x), we need to iterate the equationuntil the difference between x n and x n+1 is small. In pseudo-code this would bewhile(delta > .00001) {

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

Saved successfully!

Ooh no, something went wrong!