library(bootstrap)


cvec<-seq(0.2,1,by=0.025)
mse<-cvec*0

B<-20000

n<-164
m<-20
r<-order(cholost$z)
x<-cholost$z[r]
y<-cholost$y[r]

for(i in 1:length(cvec)){
	ico<-0
	msv<-0
	for(b in 1:B){

		msvb<-NA
		while(is.na(msvb)){
			ind<-sort(sample(index,size=m,rep=F))
			xtest<-x[ind]
			ytest<-y[ind]
			xtrain<-x[-ind]
			ytrain<-y[-ind]
	
			y.fit<-predict(loess(ytrain~xtrain,span=cvec[i]),xtest)

			msvb<-sum((y.fit-ytest)^2)
			if(is.na(msvb)) ico<-ico+1
		}
		msv<-msv+msvb
	}	
	mse[i]<-msv/B
	print(c(i,cvec[i],mse[i],ico))
}


postscript("Boot-cholost-boot-cv.ps")
plot(cvec,mse,type="l",xlab="span")
points(cvec,mse,pch=19)
dev.off()

best.span<-cvec[which.min(mse)]

postscript("Boot-cholost-boot-cvfit.ps")
plot(y ~ z, data=cholost, xlab="Compliance", 
            ylab="Improvement",pch=19)

B<-200
for(b in 1:B){

	ind<-sort(sample(index,size=n,rep=T))
	xboot<-x[ind]
	yboot<-y[ind]

	X.fitboot<-predict(loess(yboot~xboot,span=best.span),xv)

	lines(xv,X.fitboot,col="red",lwd=1)


}
dev.off()


