string formula not evaluated in global environment?

前端 未结 2 684
终归单人心
终归单人心 2021-01-25 15:44

The string formula in the loop throws an error with standardize(), whereas the non-loop versions do not. Environment issue?

library(arm)
set.seed(1)         


        
相关标签:
2条回答
  • 2021-01-25 16:31

    It is important that the formula is actually substituted in the lm object:

    for (i in list(quote(x1), quote(x2))) {
        f <- bquote(y ~ .(i))
        m0 <- eval(bquote(lm(.(f), data=df)))
        m0z <- arm::standardize(m0)
    }
    
    0 讨论(0)
  • 2021-01-25 16:44

    A solution is to not use string formulas, but rather to construct a formula from an expression, and evaluate that:

    f = eval(bquote(y ~ .(as.name(i))))
    

    This works because f will be constructed in the current environment.

    Alternatively, just call as.formula(f) manually instead of passing the naked f to lm; however, I always dislike going the detour via strings. This is an anti-pattern known as stringly typing.

    0 讨论(0)
提交回复
热议问题