0

I have this dataset:

 structure(list(V1 = c(8L, 1L, 2L), V2 = c(25860932, 5748800, 
4042125), V3 = c(1L, 1L, 1L), V4 = c(0L, 0L, 0L), V5 = c("M2", 
"W5", "W5"), V6 = c("Electrical&Electronics", "Food&Beverages&Agri", 
"Food&Beverages&Agri")), .Names = c("V1", "V2", "V3", "V4", "V5", 
"V6"), row.names = c(NA, 3L), class = "data.frame")

I would like to build a logistic regression model with V4 as the dependent variable by choosing various combinations of the other variables:

Taking one independent variable at a time:
Model 1: V4 ~ V1
Model 2: V4 ~ V2
Model 3: V4 ~ V3
Model 4: V4 ~ V5

Taking two independent variables at a time:
Model 1: V4 ~ V1 + V2
Model 2: V4 ~ V1 + V3
Model 3: V4 ~ V1 + V5
Model 4: V4 ~ V2 + V3
Model 5: V4 ~ V2 + V5
Model 6: V4 ~ V3 + V5

Taking three independent variables at a time:
Model 1: V4 ~ V1 + V2 + V3
Model 2: V4 ~ V1 + V2 + V5
Model 3: V4 ~ V1 + V3 + V5
Model 4: V4 ~ V2 + V3 + V5

Taking 4 independent variables at a time:
Model 1: V4 ~ V1 + V2 + V3 + V5

How do I do this automatically in R without explicitly typing the combinations?

Kenneth Singh
  • 335
  • 1
  • 3
  • 15
  • Also see [this link](https://ryouready.wordpress.com/2009/02/06/r-calculating-all-possible-linear-regression-models-for-a-given-set-of-predictors/). – Maurits Evers Mar 15 '18 at 12:02
  • Also related is [How to run lm models using all possible combinations of several variables and a factor Ask Question](https://stackoverflow.com/questions/28606549/how-to-run-lm-models-using-all-possible-combinations-of-several-variables-and-a) – Maurits Evers Mar 15 '18 at 12:03

1 Answers1

0

you can try with combn et as.formula:

vars <- t(combn(c('V1','V2', 'V3'), 2))

forms <- apply(vars, MARGIN = 1, function(x) {
  tmp <- paste(x, collapse = '+')
  as.formula(paste0('V4 ~',tmp))

})

glm(formula = forms[[1]], data= ...)
Antoine N.
  • 151
  • 8