The Art of R Programming

(WallPaper) #1
71 # regress, leaving out ith observation
72 lmo <- lm(y[-i] ~ xmat[-i,])
73 betahat <- as.vector(lmo$coef)
74 # the 1 accommodates the constant term
75 predy[i] <- betahat %*% c(1,xmat[i,])
76 }
77 return(predy)
78 }
79
80 # polynomial function of x, coefficients cfs
81 poly <- function(x,cfs) {
82 val <- cfs[1]
83 prod <- 1
84 dg <- length(cfs) - 1
85 for (i in 1:dg) {
86 prod <- prod*x
87 val <- val + cfs[i+1]*prod
88 }
89 }

As noted, the only new code isplot.polyreg(). For convenience, the code
is reproduced here:

# generic plot(); plots fits against raw data
plot.polyreg <- function(fits) {
plot(fits$x,fits$y,xlab="X",ylab="Y") # plot data points as background
maxdg <- length(fits) - 2
cols <- c("red","green","blue")
dg <- curvecount <- 1
while (dg < maxdg) {
prompt <- paste("RETURN for XV fit for degree",dg,"or type degree",
"or q for quit ")
rl <- readline(prompt)
dg <- if (rl == "") dg else if (rl != "q") as.integer(rl) else break
lines(fits$x,fits[[dg]]$fitted.values,col=cols[curvecount%%3 + 1])
dg <- dg + 1
curvecount <- curvecount + 1
}
}

As before, our implementation of the generic function takes the name
of the class, which isplot.polyreg()here.
Thewhileloop iterates through the various polynomial degrees. We
cycle through three colors, by setting the vectorcols; note the expression
curvecount %%3for this purpose.

268 Chapter 12

Free download pdf