# 계량경제학 강의 R 코드

# 제12장 이분산

# 12.3 이분산에 견고한 분산추정 방법

# 예제 12.3 이분산에 견고한 표준오차

data(Housing,package="Ecdat")
nrow(Housing)
names(Housing)
ols <- lm(log(price)~log(lotsize)+bedrooms+bathrms,data=Housing)
coeftest(ols)
#install.packages('sandwich')
library(sandwich)
coeftest(ols,vcov=vcovHC(ols,type="HC0"))
library(car)
hccm(ols,type="hc0")

# 12.4 표본이 크지 않을 때 HC 분산추정량 교정하기

# 예제 12.4 통상적인 표준오차와 여러 견고한 표준오차들의 비교

library(sandwich)
data(Housing,package="Ecdat")
ols <- lm(log(price)~log(lotsize)+bedrooms+bathrms,data=Housing)
se <- sqrt(diag(vcov(ols)))
hse0 <- sqrt(diag(vcovHC(ols,type="HC0")))
hse1 <- sqrt(diag(vcovHC(ols,type="HC1")))
hse2 <- sqrt(diag(vcovHC(ols,type="HC2")))
hse3 <- sqrt(diag(vcovHC(ols,type="HC3")))
hse4 <- sqrt(diag(vcovHC(ols,type="HC4")))
round(cbind(se,hse0,hse1,hse2,hse3,hse4),5)

# 12.5 이분산하에서 OLS를 이용한 가설검정

# 예제 12.5 지역별 사망률

datadir <- "http://econ.korea.ac.kr/~chirokhan/book/data"
Death <- read.csv(file.path(datadir,"deathrate.csv"))
model <- deathrate~drink+smoke+aged+vehipc+factor(year)
ols <- lm(model,data=Death)
library(lmtest)
coeftest(ols)
library(sandwich)
coeftest(ols,vcov=vcovHC)

# 예제 12.6 사망률 분석에서 F검정

library(car)
lht(ols,c("drink","smoke"))
library(sandwich)
waldtest(ols,c("drink","smoke"),vcov=vcovHC)

# 12.6 이분산하에서 BLUE 구하기: 가중최소제곱법

# 예제 12.8 사망률 모형의 WLS 추정

model <- deathrate~drink+smoke+aged+vehipc+factor(year)
wls <- lm(model,data=Death,weights=regpop)
coeftest(wls)

# 12.7 분산의 구조를 모를 때 GLS하기: FGLS

# 예제 12.9 하나의 FGLS

model <- deathrate~drink+smoke+aged+vehipc+factor(year)
## Step 1
ols <- lm(model,data=Death)
Death$u <- ols$resid
## Step 2
aux <- lm(update(model,I(log(u^2))~.),data=Death)
Death$g <- aux$fitted
## Step 3
Death$h <- exp(Death$g)
## Step 4
fgls <- lm(model,data=Death,weight=1/h)
library(lmtest)
coeftest(fgls)

# 12.8 이분산이 존재하는지 검정

set.seed(101)
n <- 50
x1 <- rnorm(n)
x2 <- rnorm(n)
u <- x1*rnorm(n)
y <- 1+x1-x2+u
bptest(y~x1+x2,~x1+I(x1^2))
u2 <- lm(y~x1+x2)$resid^2
aux <- lm(u2~x1+I(x1^2))
n*summary(aux)$r.sq