简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM