如何从 lm_robust 对象获取 AIC

How to get AIC from lm_robust object

如何从 lm_robust 对象(包 estimatr)中获取 AIC?我使用 lm_robust 是因为我想使用稳健的估算器来计算 SE。与 lm 函数不同,当您 运行 汇总函数和 lm_robust 对象上的 AIC 函数生成 运行 时,不提供 AIC一个错误。下面是我正在尝试的那种模型的玩具示例 运行。

library(estimatr)

fake_data<-data.frame(outcome=rnorm(100,3.65,1),
                      pred1=rnorm(100,15,7),
                      pred2=as.factor(sample(1:5, 100, replace = T)))

mod1<-lm_robust(outcome~pred1+pred2,data=fake_data)
AIC(mod1)

错误消息如下所示:

> AIC(mod1)
Error in UseMethod("logLik") : 
  no applicable method for 'logLik' applied to an object of class "lm_robust"

这是一个解决方法

mod1 = lm_robust(outcome ~ pred1 + pred2, data = fake_data)

#Create any fitted model using 'lm' as a placeholder
mod2 = with(list(x = rnorm(10), y = rnorm(10)), lm(y ~ x))

#Copy values in `mod2` from `mod1`
mod2[names(mod2)] = mod1[names(mod2)]

#Calculate residuals in `mod2`
mod2$residuals = mod2$fitted.values - fake_data$outcome

AIC(mod2)
#[1] 326.6092

如果一定要用lm_robust,可以选择自己计算如下,

公式AIC,

AIC = 2*k + n [Ln( 2(pi) RSS/n ) + 1]

# n : Number of observation
# k : All variables including all distinct factors and constant
# RSS : Residual Sum of Square

如果我们将它应用到 R 你的情况,

# Note that, I take k=7 since you have, 5 factors + 1 continuous and 1 constant

AIC_calculated <- 2*7 + 100* (log( 2*pi* (1-mod1$r.squared)*mod1$tss/100 ) + 1)


[1] 332.2865

这与 lmglm 输出相同。

mod2<-lm(outcome~pred1+pred2,data=fake_data)

> AIC(mod2)
[1] 332.2865

最后,当然,您可以将此计算放入一个函数中,只需在其中提供 lm_robust 模型即可随时调用,而无需设置 Nk 任何给定数据的参数,例如

myAIC <- function(data) {

    2*(data$k+1) + data$N * (log(2*pi* (1-data$r.squared)*data$tss/data$N ) + 1)

}

> myAIC(mod1)
[1] 332.2865

注意: 由于在数据帧中 运行 sample() 函数时的播种差异,结果在您的计算机中可能显示不同。