简体   繁体   中英

How to evaluate in a formula in r

Say there is a formula:

f1 = as.formula(y~ var1 + var2 + var3)
f1
## y ~ var1 + var2 + var3

Then I want to update the formula by adding a named vector a .

a = 'aaabbbccc'
f2 = update(f1, ~ . + a)
f2
## y ~ var1 + var2 + var3 + a

This is not what I expected. I want a to be evaluated in the formula. Then I tried this:

f3 = update(f1, ~ . + get(a))
f3
## y ~ var1 + var2 + var3 + get(a)

Also failed. What I expected is this:

y ~ var1 + var2 + var3 + aaabbbccc

Any help will be highly appreciated!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM