Aru Bhardwaj
Aru Bhardwaj

Reputation: 55

How to run all possible combinations in multiple linear regression model in R

I have a data set of 7 variables and I want to run all possible combinations. What I exactly want is to run is different equations which choose different variables, for instance:

Y = b_0 + b_1*X_1 + b_2*X_2
Y = b_0 + b_1*X_1 + b_2*X_3
Y = b_0 + b_1*X_1 + b_2*X_2 + b_3*X_3
Y = b_0 + b_1*X_1 + b_2*X_2 + b_3*X_3 + b_2*X_4
Y = b_0 + b_1*X_1 + b_2*X_2 + b_2*X_4 
Y = b_0 + b_1*X_1 + b_2*X_4

All possible combination in this order. How should I setup my loop function?

Upvotes: 1

Views: 2092

Answers (1)

Vincent
Vincent

Reputation: 17805

Generate example data:

dat <- data.frame(
  Y = rnorm(100),
  X_1 = rnorm(100),
  X_2 = rnorm(100),
  X_3 = rnorm(100),
  X_4 = rnorm(100),
  X_5 = rnorm(100),
  X_6 = rnorm(100),
  X_7 = rnorm(100)
)

Find all 1 through 7 combinations of variables and paste them into a formula with Y as dependent variable:

variables <- colnames(dat)[2:ncol(dat)]
formulas <- list()
for (i in seq_along(variables)) {
  tmp <- combn(variables, i)
  tmp <- apply(tmp, 2, paste, collapse="+")
  tmp <- paste0("Y~", tmp)
  formulas[[i]] <- tmp
}
formulas <- unlist(formulas)
formulas <- sapply(formulas, as.formula)

Estimate 127 regression models:

models <- lapply(formulas, lm, data=dat)

Upvotes: 7

Related Questions