install.packages("caret")
library("caret")

# Stepwise Linear Regression

# load data
data(longley)
datos <- longley
# fit model
fit_inicial <- lm(Employed~., datos)
# summarize the fit
summary(fit_inicial)
# perform step-wise feature selection
fit <- step(fit_inicial)
# summarize the selected model
print(fit)
summary(fit)
fit$anova

# Rango de importancia de cada variable
model <- train(Employed~., data=datos, method="lm")
# estimate variable importance
importance <- varImp(model, scale=FALSE)
# summarize importance
print(importance)
# plot importance
plot(importance)


# make predictions
predictions <- predict(fit, longley)
# summarize accuracy
mse <- mean((longley$Employed - predictions)^2)
print(mse)
