Search code examples
rloopsfor-loopglm

How to fit multiple interaction models in a loop


I have to fit n models with all the possible two way interaction term

In sort, I have 23 variables in my main effect model, and I want do add one by one interaction and check its significance Like this

model1 <- glm(y~x1+x2+...+x23)
model2 <- glm(y~x1+x2+...+x23+x1*x2)
summary(model2)
model3 <- glm(y~x1+x2+...+x23+x1*x3)
summary(model3)
#...
model73<- glm(y~x1+x2+...+x23+x22*x23)

Solution

  • To create the formulas, try

    x_vec <- sprintf("x%d", 1:23)
    base_formula <- reformulate(x_vec, response = "y")
    
    all_formulas <- combn(x_vec, 2, \(x) {
      fmla <- paste("~ . + ", paste(x, collapse = "*"))
      update(base_formula, fmla)
    }, simplify = FALSE)
    
    all_formulas <- c(base_formula, unlist(all_formulas))
    head(all_formulas)
    #> [[1]]
    #> y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    #>     x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    #>     x22 + x23
    #> 
    #> [[2]]
    #> y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    #>     x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    #>     x22 + x23 + x1:x2
    #> 
    #> [[3]]
    #> y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    #>     x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    #>     x22 + x23 + x1:x3
    #> 
    #> [[4]]
    #> y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    #>     x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    #>     x22 + x23 + x1:x4
    #> 
    #> [[5]]
    #> y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    #>     x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    #>     x22 + x23 + x1:x5
    #> 
    #> [[6]]
    #> y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    #>     x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    #>     x22 + x23 + x1:x6
    

    Created on 2022-12-08 with reprex v2.0.2

    Then fit the models with lapply. Something like this (untested, since there are no data).

    model_list <- lapply(all_formulas, \(f) glm(f))
    smry_list <- lapply(model_list, summary)
    smry_list[[1]]