Reputation: 1453
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:
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(y ~ x | country,
data = MyData)
However, when I try to combine both the formula()
function and the fixed effects argument, I get an error:
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. How can I use the formula()
function in felm()
and still work with the convenient fixed effects syntax of that 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.
p.s.: This works in plm()
by the way so I'm guessing there is something odd in the felm()
function or I input it badly.
library("plm")
plm(formula(testformula),
data = MyData,
index = c("country"),
model = "within",
effect = "individual")
Upvotes: 2
Views: 715
Reputation: 72673
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
Upvotes: 1