string formula not evaluated in global environment?

前端 未结 2 716
终归单人心
终归单人心 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: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.

提交回复
热议问题