5

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
MyQ
  • 459
  • 3
  • 13

2 Answers2

8

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
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
2
vec = all.vars(f)
reformulate(c(vec[2:3], paste(vec[2:3], collapse = "*")), vec[1])
#y ~ a + b + a * b
d.b
  • 32,245
  • 6
  • 36
  • 77