【问题标题】:Use the formula("string") with felm() from the lfe package while also using fixed effects将公式(“字符串”)与 lfe 包中的 felm() 一起使用,同时还使用固定效果
【发布时间】:2020-07-20 12:57:26
【问题描述】:

我正在尝试运行在其他地方创建为长字符串的大型回归公式。我还想使用“固定效果”(个别特定截距)。

没有固定效果,这在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)

如果我使用国家固定效果,felm() 中的这种回归也没有问题:

felm(y ~ x | country,
     data = MyData)

但是,当我尝试结合 formula() 函数和固定效果参数时,我得到一个错误:

felm(formula(testformula) | country ,
     data = MyData)

"Error in terms(formula(as.Formula(formula), rhs = 1), specials = "G") : 
Object 'country' not found"

我觉得这很奇怪,分开来说,这两个论点都有效。如何在felm() 中使用formula() 函数,并且仍然使用该函数方便的固定效果语法?我不想将固定效果写入公式,因为我想依赖 lfe 包的内部转换。

ps:顺便说一句,这在plm() 中有效,所以我猜felm() 函数中有一些奇怪的东西,或者我输入错误。

library("plm")

plm(formula(testformula),
    data =  MyData,
    index = c("country"),
    model = "within",
    effect = "individual")

【问题讨论】:

  • 有什么不方便写testformula &lt;- "y ~ x | country"??
  • aaaaah,那部分是公式的一部分!我只是不想写`testformula
  • 有时候生活比你想象的要容易! ;)
  • 试着告诉我还在恢复的自我! ;)

标签: r panel-data


【解决方案1】:

由于固定效应是公式*的一部分,我们可以将它们包含在公式字符串中。

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

*你可以从R中的函数参数通常用逗号分隔这一事实看出这一点

【讨论】:

    猜你喜欢
    • 2017-10-18
    • 2015-08-10
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多