Home > Software engineering >  feols with step-wise fixed effects not working with custom formula
feols with step-wise fixed effects not working with custom formula

Time:10-14

I need to feed a custom formula to feols and have it estimate multiple models (various fixed effects), but this seems to break the sw() function. Compare:

library(fixest)
feols(mpg ~ disp | sw(gear, gear   carb), data = mtcars)

(That works.) This does not work:

feols(as.formula("mpg ~ disp") | sw(gear, gear   carb), data = mtcars) 

Why? And how can I get that structure of formula input to work?

CodePudding user response:

We may need paste to paste the strings togeher

library(fixest)
feols(as.formula(paste("mpg ~ disp", "sw(gear, gear   carb)", 
     sep = "|")), data = mtcars)

-output

Standard-errors: Clustered (gear) 
Fixed-effects: gear
      Estimate Std. Error  t value Pr(>|t|) 
disp -0.040774   0.015421 -2.64404  0.11821 
---
Fixed-effects: gear   carb
      Estimate Std. Error  t value Pr(>|t|) 
disp -0.018388   0.016009 -1.14861  0.36955 

which gives same as

> feols(mpg ~ disp | sw(gear, gear   carb), data = mtcars)
Standard-errors: Clustered (gear) 
Fixed-effects: gear
      Estimate Std. Error  t value Pr(>|t|) 
disp -0.040774   0.015421 -2.64404  0.11821 
---
Fixed-effects: gear   carb
      Estimate Std. Error  t value Pr(>|t|) 
disp -0.018388   0.016009 -1.14861  0.36955 

NOTE: paste is more efficient compared to reformulate. If it is a single expression, formula can be used an expression i.e.

fmla <- mpg ~ disp | sw(gear, gear   carb)
> feols(fmla, data = mtcars)
Standard-errors: Clustered (gear) 
Fixed-effects: gear
      Estimate Std. Error  t value Pr(>|t|) 
disp -0.040774   0.015421 -2.64404  0.11821 
---
Fixed-effects: gear   carb
      Estimate Std. Error  t value Pr(>|t|) 
disp -0.018388   0.016009 -1.14861  0.36955 

CodePudding user response:

In general, I marginally prefer reformulate() to as.formula(paste()) syntax.

fml <- reformulate(
    "disp | sw(gear, gear   carb)",
    response = "mpg"
)
feols(fml, data = mtcars)

From the reformulate docs:

reformulate creates a formula from a character vector.

Although in this particular case the issue is simply that you cannot mix as.formula() into the same function call as a formula object. You could do this without paste() simply by including the whole term in as.formula():

feols(as.formula("mpg ~ disp | sw(gear, gear   carb)"), data = mtcars) 

Output for both is:

Standard-errors: Clustered (gear)
Fixed-effects: gear
      Estimate Std. Error  t value Pr(>|t|) 
disp -0.040774   0.015421 -2.64404  0.11821 
---
Fixed-effects: gear   carb
      Estimate Std. Error  t value Pr(>|t|) 
disp -0.018388   0.016009 -1.14861  0.36955
  • Related