The formula object in R allows variables to be specified flexibly e.g. y ~ factor(X) or y ~ log(X). Doing this when fitting models for mediate, however, results in error.
This example from the package documentation works as expected:
The root cause has to do with how model.frame() handles column names. For example:
> model.m <- lm(job_seek ~ treat + depress1 + econ_hard + factor(sex) + age
+ + occp + marital + nonwhite + educ + income, data = jobs)
> test <- predict(model.frame())
Error in terms.formula(formula, data = data) :
argument is not a valid model
> test <- predict(model.m)
> test <- predict(model.m, newdata = model.frame(model.m))
Error in factor(sex) : object 'sex' not found
The
formula
object in R allows variables to be specified flexibly e.g.y ~ factor(X)
ory ~ log(X)
. Doing this when fitting models formediate
, however, results in error.This example from the package documentation works as expected:
But would break if we replace
sex
withfactor(sex)
:Or, if we try replacing age with log(age):
The root cause has to do with how
model.frame()
handles column names. For example: