我有一个差分模型,我想用R的固定效应来估计,我想包括暴露和治疗的相互作用,来计算领先和滞后效应。
基本上,我的变量是共线的,并且希望选择从我的模型中排除哪一个变量。几天前,对于lfe包来说,这是非常简单的,您可以这样做:
library(data.table)
library(fixest)
crime <- fread("crime.csv")
# Time as a factor for fixed effects
crime[, time := factor(time)]
# Model
xx <- model.matrix(any_crime ~ treatment:time - 1, data = crime) # time is a factor
# Set period 12 as base
xx[, "treatment:time12"] <- 0
# Model with leads and lags
m1 <- felm(any_crime ~ xx | id + time, data = crime)但是,现在lfe已经归档,我已经转向了fixest包,它要快得多。然而,我不能让feols()接受我的model.matrix。在执行与上面相同的操作时,用feols()替换felm()会导致以下错误:
> feols(any_crime ~ xx | id + time, data = crime)
Error in feols(any_crime ~ xx | id + time, data = crime)
The variable xx is in the RHS of the formula but not in the dataset.我读过?feols()和公式论点,没有提到模型矩阵,细节部分只有一句长。
fixest也有model.matrix.fixest,我也检查了这个函数的帮助,它说它接受一个fixest对象作为它的第一个参数。我无法使用它来创建一个将周期12设置为基期的模型。
这里是一个小样本的数据重现性。
谢谢你们所有人。
发布于 2020-12-11 16:12:35
fixest估计公式中的所有变量必须在数据集中:与lm或felm相反,不存在来自全局环境的评估。
但是您的情况可以很容易地处理函数i()。下面是来自格列奈特的一个例子
library(fixest)
data(base_did)
est_did = feols(y ~ x1 + i(treat, period, 5) | id + period, base_did)
est_did
#> OLS estimation, Dep. Var.: y
#> Observations: 1,080
#> Fixed-effects: id: 108, period: 10
#> Standard-errors: Clustered (id)
#> Estimate Std. Error t value Pr(>|t|)
#> x1 0.973490 0.045678 21.312000 < 2.2e-16 ***
#> treat:period::1 -1.403000 1.110300 -1.263700 0.209084
#> treat:period::2 -1.247500 1.093100 -1.141200 0.256329
#> treat:period::3 -0.273206 1.106900 -0.246813 0.805526
#> treat:period::4 -1.795700 1.088000 -1.650500 0.101769
#> treat:period::6 0.784452 1.028400 0.762798 0.447262
#> treat:period::7 3.598900 1.101600 3.267100 0.001461 **
#> treat:period::8 3.811800 1.247500 3.055500 0.002837 **
#> treat:period::9 4.731400 1.097100 4.312600 3.6e-05 ***
#> treat:period::10 6.606200 1.120500 5.895800 4.4e-08 ***
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> Log-likelihood: -2,984.58 Adj. R2: 0.48783
#> R2-Within: 0.38963函数i()执行一个连续变量(尽管它也可以是一个因子)和一个因子(第二个元素总是作为一个因子处理)之间的交互。然后可以添加参数ref和/或drop和/或keep,以指定要保留的因子的级别。( ref和drop之间的区别是微妙的:ref只接受一个值,drop接受很多,在估计时使用coefplot时会突出显示引用。)
在前面的例子中,我们有ref = 5,所以第五个周期将被排除在交互之外。
回到您的示例,以下内容应该可以工作(不需要创建任何额外的数据):
feols(any_crime ~ i(treatment, time, 12) | id + time, data = crime)这样就很容易重新建立或丢弃以下几个:
feols(any_crime ~ i(treatment, time, 10) | id + time, data = crime)
feols(any_crime ~ i(treatment, time, drop = 10:12) | id + time, data = crime)https://stackoverflow.com/questions/65226922
复制相似问题