4

I'm running a step regression and I'd like to extract the final formula to use it in another regression.

Using this example:

lm1 <- lm(Fertility ~ ., data = swiss)
slm1 <- step(lm1)

I would expect to be able to assign this to a formula object:

Fertility ~ Agriculture + Education + Catholic + 
    Infant.Mortality
Pierre Lapointe
  • 16,017
  • 2
  • 43
  • 56

2 Answers2

9

You can simply extract it from your slm1 object using the formula method for lm object

formula(slm1)
Fertility ~ Agriculture + Education + Catholic + Infant.Mortality
dickoa
  • 18,217
  • 3
  • 36
  • 50
  • @PLapointe You are welcome. In R there's always more than one way to do it... :) – dickoa Jul 03 '13 at 20:38
  • @dickoa -- Yours isn't just another solution: it's the better one. [As discussed here](http://stackoverflow.com/questions/17395724/any-pitfalls-to-using-programatically-constructed-formulas/17458699#17458699), the `call` element (used in P. Lapointe's answer) doesn't reliably capture the actually active formula. – Josh O'Brien Jul 04 '13 at 00:28
4

Got it:

> as.formula(slm1$call)
Fertility ~ Agriculture + Education + Catholic + Infant.Mortality
Pierre Lapointe
  • 16,017
  • 2
  • 43
  • 56