The Art of R Programming

(WallPaper) #1
Note first that we used a common R trick in this command:

> (lmo <- polyfit(y,x,dg))

By surrounding the entire assignment statement in parentheses, we get
the printout and formlmoat the same time, in case we need the latter for
other things.
The functionpolyfit()fits polynomial models up through a specified
degree, in this case 15, calculating the cross-validated mean squared pre-
diction error for each model. The last few values in the output were NA,
because roundoff error considerations led R to refuse to fit polynomials of
degrees that high.
So, how is it all done? The main work is handled by the function
polyfit(), which creates an object of class"polyreg". That object consists
mainly of the objects returned by the R regression fitterlm()for each
degree.
In forming those objects, note line 14:

lmo$fitted.cvvalues <- lvoneout(y,pwrs[,1:i,drop=F])

Here,lmois an object returned bylm(), but we are adding an extra com-
ponent to it:fitted.cvvalues. Since we can add a new component to a list at
any time, and since S3 classes are lists, this is possible.
We also have a method for the generic functionprint(),print.polyreg()
in line 24. In Section 12.1.5, we will add a method for theplot()generic
function,plot.polyreg().
In computing prediction errors, we used cross-validation, or the leaving-
one-out method, in a form that predicts each observation from all the oth-
ers. To implement this, we take advantage of R’s use of negative subscripts in
line 57:

lmo <- lm(y[-i] ~ xmat[-i,])

So, we are fitting the model with theithobservation deleted from our
data set.

NOTE As mentioned in the comment in the code, we could make a much faster implemen-
tation by using a matrix-inverse update method, known as the Sherman-Morrison-
Woodbury formula. For more information, see J. H. Venter and J. L. J. Snyman,
“A Note on the Generalised Cross-Validation Criterion in Linear Model Selection,”
Biometrika, Vol. 82, no. 1, pp. 215–219.

9.2 S4 Classes.................................................................


Some programmers feel that S3 does not provide the safety normally as-
sociated with OOP. For example, consider our earlier employee database

222 Chapter 9

Free download pdf