How to evaluate in a formula in r
If you are evaluating these statements in your global environment, then you could do:
f <- y ~ var1 + var2 + var3
a <- as.name("aaabbbccc")
update(f, substitute(~ . + a, env = list(a = a)))
## y ~ var1 + var2 + var3 + aaabbbccc
Otherwise, you could do:
update(f, substitute(~ . + a, env = environment()))
## y ~ var1 + var2 + var3 + aaabbbccc
The important thing is that the value of a
in env
is a symbol, not a string: as.name("aaabbbccc")
or quote(aaabbbccc)
, but not "aaabbbccc"
.
Somewhat unintuitively, substitute(expr, env = .GlobalEnv)
is equivalent to substitute(expr, env = NULL)
. That is the only reason why it is necessary to pass list(a = a)
(or similar) in the first case.
I should point out that, in this situation, it is not too difficult to create the substitute
result yourself, "from scratch":
update(f, call("~", call("+", quote(.), a)))
## y ~ var1 + var2 + var3 + aaabbbccc
This approach has the advantage of being environment-independent, and, for that reason, is probably the one I would use.