Mr.Spock
Mr.Spock

Reputation: 521

Extract the formula for stepwise optimized regression model

I performed a multiple linear regression. My real dataframe contains a lot of more x-values.

Regression <- lm(df1$y ~ df2$x1 + df2$x2 + df2$x3 + df2$x4 + df2$x5 + df2$x6)

StepRegression=step(Regression,direction="both")

#Or with the MASS package
library(MASS)
step.model <- stepAIC(Regression, direction = "both", trace = FALSE)
step.model

My question is now, how do I automatically get the optimized model? I tired this:

library(MASS)
OptiRegression = step.model$call

But this only gives me this:

lm(formula =df1$y ~ df2$x1 + df2$x3 + df2$x5)

summary(test)
Length  Class   Mode 
     2   call   call 

But I want to get the summary of the updated model, with the coefficients which I get for example when I typ in:

OptiRegression = lm(df1$y ~ df2$x1 + df2$x3 + df2$x5)
summary (OptiRegression)

Upvotes: 0

Views: 591

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76641

I believe you are trying to do something like any of the following two regressions. I will use the built-in dataset mtcars since you have not posted one.

library(MASS)

Regression <- lm(mpg ~ ., data = mtcars)

StepRegression <- step(Regression, direction = "both")

OptiReg1 <-StepRegression$terms
fit1 <- lm(OptiReg1, data = mtcars)

As you can see, both summaries are equal, only the formula changes.

summary(StepRegression)
summary(fit1)

Or with the MASS package, function stepAIC.

step.model <- stepAIC(Regression, direction = "both", trace = FALSE)

OptiReg2 <- step.model$terms
fit2 <- lm(OptiReg2, mtcars)

Now, once again, these two summaries are in practice equal, only the formula changes. And it changes because in fit2 what is passed is OptiReg.

summary(step.model)
summary(fit2)

Upvotes: 0

Related Questions