rvlenth/emmeans

Log transform is not detected when applying emmeans to a list of models

qdread opened this issue · 6 comments

formula_string <- 'log(mpg) ~ factor(cyl)'
model <- lm(as.formula(formula_string), data = mtcars)
emmeans(model, specs = ~ cyl, type = 'response')

formula_string_list <- list('log(mpg) ~ factor(cyl)', 'log(disp) ~ factor(cyl)')
models <- lapply(formula_string_list, function(form) lm(as.formula(form), data = mtcars))
lapply(models, function(mod) emmeans(mod, specs = ~ cyl, type = 'response'))

In the above, I get the expected output with back-transformed emmeans from the first call to emmeans(), where the formula is coerced from a string. However in the second case, where the lm() function is applied to a list of strings coerced to formulas, the log transformation is not detected and the means are not back-transformed. I tried to work around this using regrid() and summary(type = 'r') but could not find a workable solution. Thanks in advance for your help!

Tracing this for models, I get the error message:

Error in eval(mf, parent.frame()) : object 'form' not found

That is, we have lost the environment of your function call. I modified the code so the evaluation is done in environment(trms) where trms is based on the terms() component, and it seems to work now:

> ref_grid(model)
'emmGrid' object with variables:
    cyl = 4, 6, 8
Transformation: “log” 

> ref_grid(models[[1]])
'emmGrid' object with variables:
    cyl = 4, 6, 8
Transformation: “log” 

So it is fixed in the next push to GitHub, as long as this fix doesn't break something else...

The workable solution by the way is to explicitly specify the transformation:

lapply(models, function(mod) emmeans(mod, specs = ~ cyl, type = 'response', tran = 'log'))

Thank you for tracking down the source of the problem, fixing it, and providing a more robust solution! What more could one ask for

Oops I did not mean to close the issue

OK. But if you're not closing, does that mean that there's more to do to address the issue? If so, I'm not seeing it.

No it is all good! Thanks for addressing. Closed again ;-)