jmbejara / comp-econ-sp18

Main Course Repository for Computational Methods in Economics (Econ 21410, Spring 2018)
16 stars 23 forks source link

R error in fixed effects: Error: inherits(object, "formula") is not TRUE #69

Closed Jacob-Bishop closed 6 years ago

Jacob-Bishop commented 6 years ago

I'm trying to use the plm package in R to a state-fixed effects regression for question2 of the fixed effects part of the homework. My code is:

formula_2 = 'fatalityrate ~ sb_useage + factor(speed65) + factor(speed70) + factor(ba08) + factor(drinkage21) +log(income)+age' fit2 = plm(eval(formula_2), data=df, model="within", effect="individual", index=c('state'))

and I'm getting "Error: inherits(object, "formula") is not TRUE"

I'm not sure what this means/what I have to fix?

jmbejara commented 6 years ago

plm (as do most regressions functions--e.g. lm) expects a formula object. Thus, you might write something like

lm(fatalityrate ~ + sb_useage)

Note that there are no quotation marks. If you want to define the formula object outside of the function call, you could do something like this: http://www.cookbook-r.com/Formulas/Creating_a_formula_from_a_string/

This issue stems from a strange quirk of R. It uses non-standard evaluation for it's function calls. This can sometimes be nice and sometimes inconvenient. See here for a description (including the benefits of lazy loading): https://youtu.be/_H8zrP1TCj8?t=23m59s

Jacob-Bishop commented 6 years ago

Thanks, that fixes the problem.

Interestingly, it appears that lm() does work correctly when given a string for a formula.

jmbejara commented 6 years ago

Gotcha. Thanks!