拟合具有稳健标准误差的模型

Fit models with robust standard errors

我正在使用以下 R 代码运行 几个线性回归模型并将结果提取到数据框:

library(tidyverse)
library(broom)

data <- mtcars
outcomes <- c("wt", "mpg", "hp", "disp")
exposures <- c("gear", "vs", "am")

models <- expand.grid(outcomes, exposures) %>%
group_by(Var1) %>% rowwise() %>%
summarise(frm = paste0(Var1, "~factor(", Var2, ")")) %>%
group_by(model_id = row_number(),frm) %>%
do(tidy(lm(.$frm, data = data))) %>%
mutate(lci = estimate-(1.96*std.error),
     uci = estimate+(1.96*std.error))

如何修改我的代码以使用类似于 STATA 的可靠标准错误?

* example of using robust standard errors in STATA
regress y x, robust

关于 lm 模型中稳健标准误差的全面讨论 at stackexchange

您可以通过以下方式更新您的代码:

library(sandwich)

models <- expand.grid(outcomes, exposures) %>%
 group_by(Var1) %>% rowwise() %>%
 summarise(frm = paste0(Var1, "~factor(", Var2, ")")) %>%
 group_by(model_id = row_number(),frm) %>%
 do(cbind(
  tidy(lm(.$frm, data = data)),
  robSE = sqrt(diag(vcovHC(lm(.$frm, data = data), type="HC1"))) )
 ) %>%
 mutate(
  lci  = estimate - (1.96 * std.error), 
  uci  = estimate + (1.96 * std.error),
  lciR = estimate - (1.96 * robSE),
  uciR = estimate + (1.96 * robSE)
 )

重要的一行是:

sqrt(diag(vcovHC(lm(.$frm, data = data), type="HC1"))) )

函数vcovHCreturns协方差矩阵。您需要提取对角线上的方差 diag 并计算平方根 sqrt