我正在使用以下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
答案 0 :(得分:3)
对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"))) )
函数vcovHC
返回协方差矩阵。您需要提取对角线diag
上的方差并计算平方根sqrt
。