gpt4 book ai didi

使用 bife 包时删除线性因变量

转载 作者:行者123 更新时间:2023-12-03 16:20:00 25 4
gpt4 key购买 nike

一些预编程模型会在 lm() 中自动删除其回归输出中的线性因变量(例如 R) .与 bife包,这似乎是不可能的。如 CRAN 中的包装说明所述第 5 页:

If bife does not converge this is usually a sign of linear dependence between one or more regressorsand the fixed effects. In this case, you should carefully inspect your model specification.


现在,假设手头的问题涉及进行许多回归,并且无法充分检查每个回归输出——必须假设某种关于回归量的经验法则。有哪些替代方法可以或多或少地自动删除线性相关回归量并实现足够的模型规范?
我设置了一个代码作为下面的例子:
#sample coding

x=10*rnorm(40)
z=100*rnorm(40)

df1=data.frame(a=rep(c(0,1),times=20), x=x, y=x, z=z, ID=c(1:40), date=1, Region=rep(c(1,2, 3, 4),10))
df2=data.frame(a=c(rep(c(1,0),times=15),rep(c(0,1),times=5)), x=1.4*x+4, y=1.4*x+4, z=1.2*z+5, ID=c(1:40), date=2, Region=rep(c(1,2,3,4),10))
df3=rbind(df1,df2)

df3=rbind(df1,df2)

for(i in 1:4) {

x=df3[df3$Region==i,]

model = bife::bife(a ~ x + y + z | ID, data = x)

results=data.frame(Region=unique(df3$Region))

results$Model = results

if (i==1){
df4=df
next
}

df4=rbind(df4,df)


}

Error: Linear dependent terms detected!

最佳答案

由于您只查看线性依赖项,因此您可以简单地利用检测它们的方法,例如 lm .
这是一个包含 fixest 包的解决方案示例:

library(bife)
library(fixest)

x = 10*rnorm(40)
z = 100*rnorm(40)

df1 = data.frame(a=rep(c(0,1),times=20), x=x, y=x, z=z, ID=c(1:40), date=1, Region=rep(c(1,2, 3, 4),10))

df2 = data.frame(a=c(rep(c(1,0),times=15),rep(c(0,1),times=5)), x=1.4*x+4, y=1.4*x+4, z=1.2*z+5, ID=c(1:40), date=2, Region=rep(c(1,2,3,4),10))

df3 = rbind(df1, df2)

vars = c("x", "y", "z")

res_all = list()
for(i in 1:4) {
x = df3[df3$Region == i, ]

coll_vars = feols(a ~ x + y + z | ID, x, notes = FALSE)$collin.var
new_fml = xpd(a ~ ..vars | ID, ..vars = setdiff(vars, coll_vars))
res_all[[i]] = bife::bife(new_fml, data = x)
}

# Display all results
for(i in 1:4) {
cat("\n#\n# Region: ", i, "\n#\n\n")
print(summary(res_all[[i]]))
}
这里需要的函数是 feolsxpd ,两个来自 fixest .一些解释:
  • feols , 喜欢 lm , 在发现变量共线时即时删除变量。它将共线变量的名称存储在槽 $collin.var 中。 (如果没有找到,则为 NULL )。
  • lm相反, feols还允许固定效果,因此您可以在查找线性依赖项时添加它:这样您就可以发现也涉及固定效果的复杂线性依赖项。
  • 我已经设置了 notes = FALSE否则 feols会提示一个关于共线性的注释。
  • feols速度很快(对于大型数据集实际上比 lm 快)所以不会对您的分析造成压力。
  • 函数xpd扩展公式并用用户提供的关联参数替换以两个点开头的任何变量名称。
  • xpd 的参数是向量,行为是用加号强制它们,所以如果 ..vars = c("x", "y")提供,公式a ~ ..vars | ID会变成a ~ x + y | ID .
  • 这里它取代了 ..vars在公式中 setdiff(vars, coll_vars)) ,这是未发现共线的变量的向量。


  • 因此,在执行 bife 之前,您会得到一个自动删除变量的算法。估计。
    最后,只是一个附带评论:通常最好将结果存储在列表中,因为它避免了副本。
    更新
    我忘了,但如果您不需要偏差校正( bife::bias_corr ),那么您可以直接使用 fixest::feglm它会自动删除共线变量:
    res_bife = bife::bife(a ~ x + z | ID, data = df3)
    res_feglm = fixest::feglm(a ~ x + y + z | ID, df3, family = binomial)

    rbind(coef(res_bife), coef(res_feglm))
    #> x z
    #> [1,] -0.02221848 0.03045968
    #> [2,] -0.02221871 0.03045990

    关于使用 bife 包时删除线性因变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64792747/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com