library(readxl)
setwd("C:/Users/User/Google 雲端硬碟/政治大學ECO/計量/期末報告")
hw<-read_excel("作業估計(補缺漏植)e.xlsx")
hw <- ts(hw, frequency=4, start=c(1777,1))

1 H0:β1=0

Y<-as.matrix(hw[,1])
X<-as.matrix(hw[,c(2:8)])
X.trans<-t(X)
XtX.inverse<-solve(X.trans%*%X)
B<-XtX.inverse%*%X.trans%*%Y

R1<-matrix(c(0,1,0,0,0,0,0),nrow = 1)
r1<-matrix(0)
e<-Y-X%*%B
e.trans<-t(e)
s1<-sqrt((e.trans%*%e)/(332-7))
m1.sqrt<-sqrt(XtX.inverse[2,2])
t.v1<-B[2]/(s1*m1.sqrt)
p.v1<-2*pt(t.v1,df = (332-7),lower.tail = F)
cat("H0:β1=0\n","t-value:",t.v1,"\n","p-value:",p.v1,"\n","So we reject the null hypothesis.")
## H0:β1=0
##  t-value: 4.738786 
##  p-value: 3.21953e-06 
##  So we reject the null hypothesis.

2 H0:all of β equal 0

r2<-matrix(c(0,0,0,0,0,0))
w.v2<-(1/6/((e.trans%*%e)/(332-7)))*(t(B[2:7])%*%solve(XtX.inverse[2:7,2:7])%*%B[2:7])
p.v2<-pf(w.v2,df1 = 6,df2 = (332-7),lower.tail = F)
cat("H0:all of β equal 0\n","F-value:",w.v2,"\n","p-value:",p.v2,"\n","So we reject the null hypothesis.")
## H0:all of β equal 0
##  F-value: 149.8095 
##  p-value: 1.937748e-90 
##  So we reject the null hypothesis.

3 H0: β1+β2=1

m3.sqrt<-sqrt(XtX.inverse[2,2]+2*XtX.inverse[2,3]+XtX.inverse[3,3])
t.v3<-(B[2]+B[3]-1)/(s1*m3.sqrt)
p.v3<-2*pt(t.v3,df = (332-7),lower.tail = F)
cat("H0: β1+β2=1\n","t-value:",t.v3,"\n","p-value:",p.v3,"\n","So we reject the null hypothesis.")
## H0: β1+β2=1
##  t-value: 4.764591 
##  p-value: 2.857367e-06 
##  So we reject the null hypothesis.

4 H0: β2=0 and β1+β2+3β3=3

r3<-matrix(c(0,3))
R3<-matrix(c(c(0,0,1,0,0,0,0),c(0,1,1,3,0,0,0)),nrow = 2,byrow = T)
R3B.r<-((R3%*%B)-r3)
w.v4<-(1/2/((e.trans%*%e)/(332-7)))*(t(R3B.r)%*%solve(R3%*%XtX.inverse%*%t(R3))%*%R3B.r)
p.v4<-pf(w.v4,df1 = 2,df2 = (332-7),lower.tail = F)
cat("H0: β2=0 and β1+β2+3β3=3\n","F-value:",w.v4,"\n","p-value:",p.v4,"\n","So we reject the null hypothesis.")
## H0: β2=0 and β1+β2+3β3=3
##  F-value: 200.5056 
##  p-value: 1.895619e-57 
##  So we reject the null hypothesis.