
## com105a of september 2024
#  with New Haven again, for stk4011

newhaven <- matrix(scan("newhaven_data",skip=5),byrow=T,ncol=3)
id <- newhaven[ ,1]
year <- newhaven[ ,2]
yy <- newhaven[ ,3]

xx <- year - 1900 # from 12 to 71 

plot(1900 + xx,yy)

xbar <- mean(xx)
xxstar <- xx-xbar # i'm centring the covariate to have sum zero 
nn <- length(xx) 

nils <- glm(yy ~ xxstar,family=gaussian)
summary(nils) 

# Coefficients:
#              Estimate Std. Error t value Pr(>|t|)    
# (Intercept) 10.644442   0.078779 135.119  < 2e-16 ***
# xxstar       0.020512   0.004549   4.509 3.22e-05 ***

ahat <- nils$coef[1]
bhat <- nils$coef[2]
res <- nils$res
Q0 <- sum(res^2)
sigmahat <- sqrt(Q0/(nn-2))

j0 <- 5 # or choose another number

xval <- seq(min(xx)-j0,max(xx)+j0)
yval <- ahat + bhat*(xval - mean(xx))

t0 <- qt(0.95,nn-2)

Mn <- sum((xx-xbar)^2) 

factor0 <- sqrt(1/nn + (xval-xbar)^2/Mn)
yvallow <- yval - factor0*sigmahat*t0
yvalup <- yval + factor0*sigmahat*t0

factor <- sqrt( 1 + 1/nn + (xval-xbar)^2/Mn )
plot(xval,factor)

ylower <- ahat + bhat*(xval-xbar) - t0*factor
yupper <- ahat + bhat*(xval-xbar) + t0*factor

aux <- seq(0,1,by=0.10) 

x0L <- min(xx) - j0
factorL <- sqrt( 1 + 1/nn + (x0L-xbar)^2/Mn )
ylowL <- ahat + bhat*(x0L-xbar) - t0*factorL #  8.19
yuppL <- ahat + bhat*(x0L-xbar) + t0*factorL # 11.67

x0R <- max(xx) + j0
factorR <- sqrt( 1 + 1/nn + (x0R-xbar)^2/Mn )
ylowR <- ahat + bhat*(x0R-xbar) - t0*factorR #  9.61
yuppR <- ahat + bhat*(x0R-xbar) + t0*factorR # 13.09

par(bty="l")
par(cex.lab=1.4142) 

plot(1900 + xx,yy,type="o",
   xlim=1900+c(min(xx)-j0, max(xx)+j0),
   ylim=c(min(ylowL), max(yuppR)), lwd=3,
   xlab="years", ylab="annual average temperature")

matlines(1900+xval,yval,type="l",lty=2,lwd=3)
matlines(1900+xval,yvallow,type="l",lty=3,col=4,lwd=3)
matlines(1900+xval,yvalup, type="l",lty=3,col=4,lwd=3)

matlines(1900+x0L+0*aux,ylowL+aux*(yuppL-ylowL),lwd=4,col=2)

matlines(1900+x0R+0*aux,ylowR+aux*(yuppR-ylowR),lwd=4,col=2)

# matlines(1900+xval,ylower,type="l",lty=3,lwd=3)
# matlines(1900+xval,yupper,type="l",lty=3,lwd=3)
