构建独立变量的各种组合的Logistic回归模型

时间:2018-03-15 11:55:08

标签: r model logistic-regression

我有这个数据集:

 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")

我想通过选择其他变量的各种组合来构建一个逻辑回归模型,其中V4作为因变量:

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

如何在不明确键入组合的情况下自动在R中执行此操作?

1 个答案:

答案 0 :(得分:0)

你可以尝试使用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= ...)