# 계량경제학 강의 R 코드

# 제13장 오차의 자기상관

# 13.1 클러스터로 묶이는 자료

# 예제 13.1 지역별 사망률

datadir <- "http://econ.korea.ac.kr/~chirokhan/book/data"
Death <- read.csv(file.path(datadir,"deathrate.csv"))
head(Death,n=10)
model <- deathrate~drink+smoke+aged+vehipc+factor(year)
ols <- lm(model,data=Death)
coeftest(ols)
coeftest(ols,vcov=vcovHC)
#install.packages("multiwayvcov")
library(multiwayvcov)
coeftest(ols,vcov=cluster.vcov(ols,Death$region,df_correction=F))

# 13.2 클러스터의 개수에 따른 조정

# 예제 13.1 클러스터의 개수에 따른 조정

coeftest(ols,vcov=cluster.vcov(ols,Death$region))

# 13.2 오차의 시계열 상관

# 시계열 상관의 검정

set.seed(101)
x <- rep(c(-1,1),50)
u <- rnorm(100)
y <- 1+x+u
library(lmtest)
dwtest(y~x)
uhat <- lm(y~x)$resid
sum(diff(uhat)^2)/sum(uhat^2)
bgtest(y~x)
bgtest(y~x,order=3)