x = c(-5.00, -4.00, -3.00, -2.00, -1.00, 0.00, 1.00, 2.00, 3.00,  4.00, 5.00)
y = c(1.05,  3.20,  1.60,  3.05,  2.45, 2.90, 2.00, 2.20, 4.60,  4.00, 3.50)
d = data.frame(x=x,y=y)
par(mfrow=c(1,1))
plot(x,y)
fit0 = lm(y~1,data=d)
fit1 = lm(y~x,data=d)
anova(fit0,fit1) # fit1 is best

resid = fit1$residuals   # for use below
beta.hat = coef(fit1)
n=5
m=2*n+1

#################################################################
#Prediction using selected model (fit1)
t0 = 8
d.new = data.frame(x=t0)
ypred = predict(fit1,d.new,se.fit=TRUE,interval="confidence")
show("Using selected model")
show(c(ypred$fit,ypred$se))


M = 10000
alpha = 0.05

par(mfrow=c(3,1))

#################################################
#Bootstrap based on selected model
y.pred = rep(NA,M)
for(j in 1:M)
{
  eps = sample(resid,m,replace=T)
  y.sim = beta.hat[1]+beta.hat[2]*x+eps
  fit = lm(y.sim~x)
  y.pred[j] = fit$coef[1]+fit$coef[2]*t0
}
yhat = mean(y.pred)
ysd = sd(y.pred)

hist(y.pred,30,xlim=c(0,7),main="Fixed model")
show("Fixed model bootstrapping")
show(c(yhat,quantile(y.pred,c(0.025,0.975)),ysd))

##########################################################
## b Bootstrapping with model selection
y.pred = rep(NA,M)
for(j in 1:M)
{
  eps = sample(resid,m,replace=T)
  y.sim = beta.hat[1]+beta.hat[2]*x+eps
  fit = lm(y.sim~x)
  if(summary(fit)$coef[2,4]<alpha)
    y.pred[j] = fit$coef[1]+fit$coef[2]*t0
  else
    y.pred[j] = mean(y.sim)
}

yhat = mean(y.pred)
ysd = sd(y.pred)
hist(y.pred,30,xlim=c(0,7),main="Model selection, semi-par")
show("Semi-parametric bootstrapping, model selection")
show(c(yhat,quantile(y.pred,c(0.025,0.975)),ysd))


##########################################################
## c  resample (x,y)     
y.pred2 = rep(NA,M)
for(j in 1:M)
{
  ind = sample(1:m,m,replace=T)
  d.sim = d[ind,]
  fit = lm(y~x,d=d.sim)
  if(summary(fit)$coef[2,4]<alpha)
    y.pred2[j] = fit$coef[1]+fit$coef[2]*t0
  else
    y.pred2[j] = mean(y.sim)
}
yhat2 = mean(y.pred2)
ysd2 = sd(y.pred2)
hist(y.pred2,30,xlim=c(0,7),main="Model selection, non-par")
show("Non-parametric bootstrapping")
show(c(yhat2,quantile(y.pred2,c(0.025,0.975)),ysd2))

