[英]Use the formula(“string”) with felm() from the lfe package while also using fixed effects
I'm trying to run a large regression formula that is created somewhere else as a long string.我正在尝试运行一个大型回归公式,该公式在其他地方作为长字符串创建。 I also want to use "fixed effects" (individual specific intercepts).
我还想使用“固定效果”(个人特定截距)。
Without fixed effects this works both in the lm()
and in felm()
functions:如果没有固定效果,这在
lm()
和felm()
函数中都有效:
library("lfe")
MyData <- data.frame(country = c("US","US","DE","DE"),
y = rnorm(4),
x = rnorm(4))
testformula <- "y ~ x"
lm(formula(testformula),
data = MyData)
felm(formula(testformula),
data = MyData)
There is also no problem with this kind of regression in felm()
if I use country fixed effects:如果我使用国家固定效应,这种回归在
felm()
中也没有问题:
felm(y ~ x | country,
data = MyData)
However, when I try to combine both the formula()
function and the fixed effects argument, I get an error:但是,当我尝试将
formula()
function 和固定效果参数结合起来时,出现错误:
felm(formula(testformula) | country ,
data = MyData)
"Error in terms(formula(as.Formula(formula), rhs = 1), specials = "G") :
Object 'country' not found"
I find this strange, separately, both of these arguments work.我觉得这很奇怪,这两个 arguments 都可以工作。 How can I use the
formula()
function in felm()
and still work with the convenient fixed effects syntax of that function?如何在 felm
felm()
) 中使用formula()
function 并仍然使用 function 的便捷固定效果语法? I don't want to write the fixed effects into the formula because I want to rely on the within transformations of the lfe package.我不想将固定效果写入公式,因为我想依赖 lfe package 的内部转换。
ps: This works in plm()
by the way so I'm guessing there is something odd in the felm()
function or I input it badly. ps:顺便说一句,这在
plm()
中有效,所以我猜 felm felm()
function 中有些奇怪,或者我输入错误。
library("plm")
plm(formula(testformula),
data = MyData,
index = c("country"),
model = "within",
effect = "individual")
Since the fixed effects are part of the formula*, we can include them in the formula string.由于固定效应是公式*的一部分,我们可以将它们包含在公式字符串中。
fit1 <- felm(y ~ x | country, data=MyData)
testformula <- "y ~ x | country"
fit2 <- felm(formula(testformula), data=MyData)
fit2
# x
# 0.3382
all.equal(fit1$coefficients, fit2$coefficients)
# [1] TRUE
*you can see this by the fact that function parameters in R are usually separated by commas *您可以通过以下事实看出这一点:R 中的 function 参数通常用逗号分隔
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.