2013-07-03 54 views
2

我正在運行一個回退步驟,我想提取最終公式以在另一個迴歸中使用它。如何從步驟迴歸中提取公式?

使用這個例子:

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

我會希望能夠將此分配給一個公式對象:

Fertility ~ Agriculture + Education + Catholic + 
    Infant.Mortality 
+0

查看作爲lm'對象一部分的調用。即:'slm1 $ call' –

+0

謝謝。唯一缺少的是'as.formula'函數。 –

回答

4

你可以簡單地提取它從你的slm1對象使用formula方法爲lm對象

formula(slm1) 
Fertility ~ Agriculture + Education + Catholic + Infant.Mortality 
+0

謝謝。這也適用。 –

+0

@PLAPOinte不客氣。在R中,總有不止一種方法可以做到這一點...... :) – dickoa

+0

@dickoa - 你不僅僅是另一種解決方案:它是更好的解決方案。 [在這裏討論](http://stackoverflow.com/questions/17395724/any-pitfalls-to-using-programatically-constructed-formulas/17458699#17458699),'call'元素(在P. Lapointe的答案中使用)不能可靠地捕獲實際活動的公式。 –

3

明白了:

> as.formula(slm1$call) 
Fertility ~ Agriculture + Education + Catholic + Infant.Mortality