glmPolynomial<-function(y,x,dg,X){
Xs<-matrix(0,length(X),dg)
xs <- matrix(0,length(x),dg)
for(i in 1:dg){
Xs[,i]<-X^i
xs[,i] <- x^i
}
fit<-glm(y~xs[,1:dg])
beta<-fit$coefficients
Xs2<-cbind(rep(1,length(X)),Xs)
predY<-t(t(Xs2)*beta)
sumupPredY<-apply(predY,1,sum)
list(beta=beta,x=X,predY=sumupPredY)
}
N <- 7
x<-seq(from=0,to=1,length=N) + rnorm(N)
y<-runif(N)+x^(N+2)*2+sin(x*6*pi)
dgs<-1:(N-1)
X <- seq(from=min(x)-0.2,to=max(x)+0.2,length=1000)
Ys <- matrix(0,length(dgs),length(X))
for(i in 1:length(dgs)){
outglm<-glmPolynomial(y,x,dgs[i],X)
Ys[i,] <- outglm$predY
}
xlim<-c(min(X),max(X))
ylim<-c(min(y)-10,max(y)+10)
par(mfcol=c(2,3))
for(i in 1:length(dgs)){
plot(X,Ys[i,],xlim=xlim,ylim=ylim,col=dgs,type="l",main=i)
points(x,y,col=2,pch=20,cex=2)
}
par(mfcol=c(1,1))