59 # the 1 accommodates the constant term
60 predy[i] <- betahat %% c(1,xmat[i,])
61 }
62 return(predy)
63 }
64
65 # polynomial function of x, coefficients cfs
66 poly <- function(x,cfs) {
67 val <- cfs[1]
68 prod <- 1
69 dg <- length(cfs) - 1
70 for (i in 1:dg) {
71 prod <- prodx
72 val <- val + cfs[i+1]*prod
73 }
74 }
As you can see,"polyreg"consists ofpolyfit(), the constructor function,
andprint.polyreg(), a print function tailored to this class. It also contains
several utility functions to evaluate powers and polynomials and to perform
cross-validation. (Note that in some cases here, efficiency has been sacrificed
for clarity.)
As an example of using the class, we’ll generate some artificial data and
create an object of class"polyreg"from it, printing out the results.
>n<-60
> x <- (1:n)/n
> y <- vector(length=n)
> for (i in 1:n) y[i] <- sin((3*pi/2)*x[i]) + x[i]^2 + rnorm(1,mean=0,sd=0.5)
>dg<-15
> (lmo <- polyfit(y,x,dg))
mean squared prediction errors, by degree
MSPE
[1,] 0.4200127
[2,] 0.3212241
[3,] 0.2977433
[4,] 0.2998716
[5,] 0.3102032
[6,] 0.3247325
[7,] 0.3120066
[8,] 0.3246087
[9,] 0.3463628
[10,] 0.4502341
[11,] 0.6089814
[12,] 0.4499055
[13,] NA
[14,] NA
[15,] NA
Object-Oriented Programming 221