gpt4 book ai didi

r - 如何在 lm_robust() 后获得带有聚类标准误差的边际效应?

转载 作者:行者123 更新时间:2023-12-03 18:25:08 26 4
gpt4 key购买 nike

我正在逐年运行带有聚集标准误差的回归。这用 Stata 很容易做到,但我必须用 R 来完成,所以我使用 lm_robust() 运行它。来自 estimatr 的函数包裹。问题是我现在必须得到一些变量的边际效应,但我不能这样做,我猜这是因为集群标准错误。我遵循了 lm_robust() 手册上的内容我已经看到他们只将 margins 包中的 margins 命令用于其他函数而没有聚集的标准错误......有没有人知道我如何获得和绘制边际效应?

set.seed(42)
library(fabricatr)
library(randomizr)
dat <- fabricate(
N = 100, # sample size
x = runif(N, 0, 1), # pre-treatment covariate
y0 = rnorm(N, mean = x), # control potential outcome
y1 = y0 + 0.35, # treatment potential outcome
z = complete_ra(N), # complete random assignment to treatment
y = ifelse(z, y1, y0), # observed outcome

# We will also consider clustered data
clust = sample(rep(letters[1:20], each = 5)),
z_clust = cluster_ra(clust),
y_clust = ifelse(z_clust, y1, y0)
)

然后当我使用 lm_robust() 运行回归时功能:
library(estimatr)
lmout_cl <- lm_robust(
y_clust ~ z_clust + x,
data = dat,
clusters = clust
)

最后,我试图获得利润......
library(margins)
mar_cl <- margins(lmout_cl)

但这会导致错误:

Error in attributes(.Data) <- c(attributes(.Data), attrib) :'names' attribute 
[1] must be the same length as the vector [0]

最佳答案

为这个阻止 margins() 的错误道歉来自与 lm_robust() 的合作estimatr 中具有非数字簇的对象0.10 及更早版本。这是由内部方式创建的estimatr::lm_robust()margins::margins()处理模型中的变量。

该错误已被解决,因此您在 estimatr 中有两个解决方案。 .

让我先生成数据。

library(fabricatr)
library(randomizr)
dat <- fabricate(
N = 100,
x = runif(N),
clust = sample(rep(letters[1:20], each = 5)),
y_clust = rnorm(N),
z_clust = cluster_ra(clust),
)

获取最新版本estimatr (v0.11.0)

https://declaredesign.org/r/estimatr 上的开发版本已修复此错误,它将在下个月左右在 CRAN 上发布。
install.packages("estimatr", dependencies = TRUE,
repos = c("http://r.declaredesign.org", "https://cloud.r-project.org"))
library(estimatr)
lmout_cl <- lm_robust(
y_clust ~ z_clust + x,
data = dat,
clusters = clust
)
library(margins)
mar_cl <- margins(lmout_cl)

使用 CRAN 版本的数字集群 estimatr (v0.10.0)

现有版本 estimatr 的解决方法在 CRAN 上是使用数字簇而不是字符簇
dat <- fabricate(
N = 100,
x = runif(N),
clust = sample(rep(1:20, each = 5)),
y_clust = rnorm(N),
z_clust = cluster_ra(clust),
)
install.packages("estimatr")
library(estimatr)
lmout_cl <- lm_robust(
y_clust ~ z_clust + x,
data = dat,
clusters = clust
)
mar_cl <- margins(lmout_cl)

关于r - 如何在 lm_robust() 后获得带有聚类标准误差的边际效应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51260518/

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