24 n <- length(fits$y)
25 tbl <- matrix(nrow=maxdeg,ncol=1)
26 cat("mean squared prediction errors, by degree\n")
27 colnames(tbl) <- "MSPE"
28 for (i in 1:maxdeg) {
29 fi <- fits[[i]]
30 errs <- fits$y - fi$fitted.xvvalues
31 spe <- sum(errs^2)
32 tbl[i,1] <- spe/n
33 }
34 print(tbl)
35 }
36
37 # generic plot(); plots fits against raw data
38 plot.polyreg <- function(fits) {
39 plot(fits$x,fits$y,xlab="X",ylab="Y") # plot data points as background
40 maxdg <- length(fits) - 2
41 cols <- c("red","green","blue")
42 dg <- curvecount <- 1
43 while (dg < maxdg) {
44 prompt <- paste("RETURN for XV fit for degree",dg,"or type degree",
45 "or q for quit ")
46 rl <- readline(prompt)
47 dg <- if (rl == "") dg else if (rl != "q") as.integer(rl) else break
48 lines(fits$x,fits[[dg]]$fitted.values,col=cols[curvecount%%3 + 1])
49 dg <- dg + 1
50 curvecount <- curvecount + 1
51 }
52 }
53
54 # forms matrix of powers of the vector x, through degree dg
55 powers <- function(x,dg) {
56 pw <- matrix(x,nrow=length(x))
57 prod <- x
58 for (i in 2:dg) {
59 prod <- prod*x
60 pw <- cbind(pw,prod)
61 }
62 return(pw)
63 }
64
65 # finds cross-validated predicted values; could be made much faster via
66 # matrix-update methods
67 lvoneout <- function(y,xmat) {
68 n <- length(y)
69 predy <- vector(length=n)
70 for (i in 1:n) {
Graphics 267