【问题标题】:How to fit multiple interaction models in a loop如何在循环中拟合多个交互模型
【发布时间】:2022-12-12 14:43:21
【问题描述】:

我必须用所有可能的双向交互项来拟合 n 个模型

总而言之,我的主效应模型中有 23 个变量,我想逐一添加交互并检查其重要性 像这样

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)

【问题讨论】:

  • glm(y~x1+x2+...+x23) 真的合适吗?数据和家庭争论在哪里?

标签: r loops for-loop glm


【解决方案1】:

要创建公式,请尝试

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

创建于 2022-12-08 reprex v2.0.2

然后用lapply拟合模型。像这样的东西(未经测试,因为没有数据)。

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

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 2019-10-20
    • 2015-09-06
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多