自动化单变量和多变量逻辑模型,return 格式化结果在 R

Automate univariate and multivariable logistic models, return formatted results in R

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

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

我正在使用 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)

}

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

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