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")