Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand the R formula

Tags:

r

It may look like an easy question but is there any fast and robust way to expand a formula like

f=formula(y ~ a * b )

to

y~a+b+ab
like image 883
MyQ Avatar asked Jan 02 '23 05:01

MyQ


2 Answers

I'd try this:

f = y ~ a * b
reformulate(labels(terms(f)), f[[2]])
# y ~ a + b + a:b

It works on more complicated formulas as well, and relies on more internals. (I'm assuming you want a useful formula object out, so in the result a:b is nicer than the ab in the question or a*b in d.b's answer.)

f = y ~ a + b * c
reformulate(labels(terms(f)), f[[2]])
# y ~ a + b + c + b:c

f = y ~ a + (b + c + d)^2
reformulate(labels(terms(f)), f[[2]])
# y ~ a + b + c + d + b:c + b:d + c:d
like image 174
Gregor Thomas Avatar answered Jan 13 '23 13:01

Gregor Thomas


vec = all.vars(f)
reformulate(c(vec[2:3], paste(vec[2:3], collapse = "*")), vec[1])
#y ~ a + b + a * b
like image 31
d.b Avatar answered Jan 13 '23 11:01

d.b