【问题标题】:Automate univariate and multivariable logistic models, return formatted results in R自动化单变量和多变量逻辑模型,在 R 中返回格式化结果
【发布时间】:2022-07-15 20:46:33
【问题描述】:

我需要从同一个数据集运行多个单变量和多变量逻辑回归模型。因此,我需要循环它以避免重复相同的代码。

我希望能够用标题清楚地标记我的输出表,以便我可以区分 RMarkdown PDF 文档中的不同模型,例如“单变量回归:Outcome = out1”,变量部分是“out1”(out1 - out3),类似于多变量模型out1 - out

的“多变量回归:结果 = out1

我正在使用 gtsummary 包,因此我可以获得格式良好的结果以及随附的脚注。

我尝试了以下方法,但没有成功。将感谢任何帮助。

# Libraries
library(gtsummary)
library(tidyverse)

# Data as well as a few artificial variables
data("iris")
my_iris <- as.data.frame(iris)

my_iris$out1 <- sample(c(0,1), 150, replace = TRUE)
my_iris$out2 <- sample(c(0,1), 150, replace = TRUE)
my_iris$out3 <- sample(c(0,1), 150, replace = TRUE)

my_iris$x1 <- sample(c(1:12), 150, replace = TRUE)
my_iris$x2 <- sample(c(50:100), 150, replace = TRUE)
my_iris$x3 <- sample(c(18:100), 150, replace = TRUE)


# This is the list of outcome variables I need to run univariate and multivariable logistic regressions for.
outcome <- c("out1", "out2", "out3")

# Univariate logistic models
for (out in seq_along(outcome)) {
my_iris %>% 
  dplyr::select(outcome[out], Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species) %>% 
  tbl_uvregression(method = glm,
                   y = outcome[out],
                   method.args = list(family = binomial),
                   exponentiate = TRUE) %>%
  bold_labels() 
}


# Multivariable logistic models
for (out in seq_along(outcome)) {
  tbl_regression(glm(outcome[out] ~ Species + Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, my_iris, family = binomial), exponentiate = TRUE)

}

【问题讨论】:

    标签: r r-markdown tidyverse gtsummary


    【解决方案1】:

    只需将它们放入函数中,然后使用任何应用函数来循环它。

    uni_tbl_model <- function(my_iris, outcome) {
      model <- glm(my_iris[,outcome] ~ Sepal.Length, my_iris, family = binomial)
      tbl <- tbl_regression(model, exponentiate = TRUE)
      tbl <- tbl %>% modify_caption(paste("Univariate Regression Model with", outcome, "as Outcome", sep = " "))
      print(tbl)
    }
    
    multi_tbl_model <- function(my_iris, outcome) {
      model <- glm(my_iris[,outcome] ~ Species + Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, my_iris, family = binomial)
      tbl <- tbl_regression(model, exponentiate = TRUE)
      tbl <- tbl %>% modify_caption(paste("Multivariable Regression Model with", outcome, "as Outcome", sep = " "))
      print(tbl)
    }
    
    sapply(outcomes, function(outcome) uni_tbl_model(my_iris, outcome))
    sapply(outcomes, function(outcome) multi_tbl_model(my_iris, outcome))
    

    【讨论】:

    • 谢谢。它很好地解决了多变量部分。但是我怎样才能使它适应单变量回归呢? tbl_uvregression 函数只需要指定结果变量,它包括模型中的所有数据框变量作为预测变量。这不是我想要的,因为我想选择一些要包含的预测变量,当然不是其他结果变量。请问我该如何解决?
    • 您不需要使用tbl_uvregression函数,只需将模型中的回归方程编辑为单变量即可。我编辑了我之前的答案以显示。
    【解决方案2】:

    也许为时已晚。 关注您的问题...

    这是我需要运行单变量和多变量逻辑回归的结果变量列表。

    outcome <- c("out1", "out2", "out3")
    
    

    这是我的建议

    使用这些向量,您可以控制在单变量和多变量模型中包含哪些变量。

    
        pred.uni<-c('Sepal.Length', 'Sepal.Width', 'Petal.Length', 'Petal.Width', 'Species')
        pred.multi<-c('Sepal.Width','Species') 
    
    

    型号

    单变量逻辑模型

    
         mod.uni.list<-list()
                    for (out in seq_along(outcome)) {
                      mod.uni.list[[out]] <- my_iris %>%
                        # dplyr::select(outcome[out], Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species) %>%
                        tbl_uvregression(
                          method = glm,
                          y = outcome[out],
                          method.args = list(family = binomial),
                          exponentiate = TRUE,
                          include = all_of(pred.uni)
                        ) %>% # include allows to choose predictor variables. Default is everything.
                        bold_labels()
                      
                    }
         names(mod.uni.list)<-outcome #This is not necessary but it could be usefull to call models later.
        
    
    ## Multivariable logistic models
    
     
    
      mod.multi.list <- list()
          for (out in seq_along(outcome)) {
            mod.multi.list[[out]] <-
              tbl_regression(glm(eval(parse(
                text = paste0(outcome[out], '~', paste(pred.multi, collapse = '+'))
              )), my_iris, family = binomial), exponentiate = TRUE)
              }
            
    

    合并两个表并使用 tab_header 添加标题,使用 tab_style 添加一些格式。

     
    
         mod.combo.list<-list()
          for (out in seq_along(outcome)) {
            mod.combo.list[[out]] <-
              tbl_merge(
                list(mod.uni.list[[out]], mod.multi.list[[out]]),
                tab_spanner = c('Univariate', 'Multivariate')
              ) %>%
              # All the styling options go after the conversion of merged table into a gt table.
              as_gt() %>% # Conversion to gt table before customizing table.
              gt::tab_style(
                style = list(# cell_fill(color = 'orange'),
                  cell_text(weight = 'bold')),
                locations = cells_body(columns = c(`p.value_1`),
                                       rows = `p.value_1` < 0.1)
              ) %>%
              gt::tab_style(
                style = list(# cell_fill(color = 'orange'),
                  cell_text(weight = 'bold')),
                locations = cells_body(columns = c(`p.value_2`),
                                       rows = `p.value_2` < 0.1)
              ) %>%
              gt::tab_header(title = md("IRIS")
                             , subtitle = md(
                               paste0(
                                 "Univariate and multivariate logistic regression 
        models on the outcome ",
                                 outcome[out]
                               )
                             )) %>%
              gt::opt_align_table_header(align = c("left"))
            
          }
          names(mod.combo.list)<-outcome #This is not necessary but it could be useful to call models later.
          
    
    

    现在你可以调用它们了。

        mod.combo.list$out1
        mod.combo.list$out2
        mod.combo.list$out3
    
    
    rbenchmark output.
    
    |test|replications|elapsed|relative|user.self|sys.self|
    |:---|:---:|:----:|:----:|:----:|----:|
    |bench.mult| 5|36.44| 1.000|  35.28|  0.95|
    |bench.combo| 5|37.42| 1.027|  36.74|  0.53|
    |bench.uni| 5|96.30| 2.643|  93.24|  2.41|
    

    正如您在 rbenchmark 输出中看到的,瓶颈在 tbl_univariate。一旦我读到这是因为该函数为每个变量运行一个模型并在每个循环之后将它们堆叠起来,就会发生这种情况。当然 Daniel D. Sjoberg 有更好的答案。 我想这也取决于硬件。这是我的笔记本电脑(i7-8550U,1.8GHz,2 核,16GB RAM)中的基准输出(5 次重复)。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      • 2021-11-29
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多