2026-03-08
wooldridgeパッケージの読み込みsandwichパッケージの読み込みlmtestパッケージの読み込みgpa3)data(gpa3)
res <- lm(cumgpa ~ sat + hsperc + tothrs + female + black + white,
data = gpa3, subset = (spring == 1))
# 通常の標準誤差
# summary(res)$coefficients[1:3, 1:2]
# 頑健な標準誤差 (sandwichパッケージを使用)
coeftest(res, vcov = vcovHC(res, type = "HC1"))[1:3, 1:2]## Estimate Std. Error
## (Intercept) 1.470064766 0.2206802109
## sat 0.001140728 0.0001915317
## hsperc -0.008566358 0.0014179275
##
## studentized Breusch-Pagan test
##
## data: res
## BP = 44.557, df = 6, p-value = 5.732e-08
# ホワイト検定(簡略版)
# 手動計算: 残差2乗を予測値とその2乗で回帰
# 残差2乗
u2 <- resid(res)^2
# 予測値
yhat <- fitted(res)
# 補助回帰
white_reg <- lm(u2 ~ yhat + I(yhat^2))
summary(white_reg)##
## Call:
## lm(formula = u2 ~ yhat + I(yhat^2))
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.26795 -0.18863 -0.12831 0.02872 2.18250
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 0.7980 0.5707 1.398 0.163
## yhat -0.5270 0.4962 -1.062 0.289
## I(yhat^2) 0.1159 0.1061 1.092 0.276
##
## Residual standard error: 0.3492 on 363 degrees of freedom
## Multiple R-squared: 0.003455, Adjusted R-squared: -0.002036
## F-statistic: 0.6292 on 2 and 363 DF, p-value: 0.5336
# LM統計量 (n * R2) と p値
n <- length(u2)
lm_stat <- n * summary(white_reg)$r.squared
p_val <- 1 - pchisq(lm_stat, df = 2)
data.frame(LM = lm_stat, p_value = p_val)## LM p_value
## 1 1.264452 0.5314075