如何解决使用 `tbl_regression` 对嵌套数据框进行多变量回归
我正在对具有一组一致自变量的结果变量列表进行多变量回归。对于单变量回归,我遵循 this example 在嵌套数据框上使用 tl_uvregression
中的 gtsummary
,但我试图将其推广到使用 tbl_regression
在嵌套数据框上的多变量回归数据框,当我尝试 unnest
表时,出现“输入必须是向量列表”的错误。以下是我尝试过的 - 我认为我遗漏了一些小而关键的步骤,但我无法弄清楚它是什么。我想要的输出是一个多变量回归输出表,每个模型作为一列,所有协变量作为行(类似于在 tbl_merge
中分别运行这些多变量模型的列表上执行 tbl_regression
) .
library(tidyverse)
library(magrittr)
library(gtsummary)
library(broom)
id <- 1:2000
gender <- sample(0:1,2000,replace = T)
age <- sample(17:64,replace = T)
race <- sample(0:1,replace = T)
health_score <- sample(0:25,replace = T)
cond_a <- sample(0:1,replace = T)
cond_b <- sample(0:1,replace = T)
cond_c <- sample(0:1,replace = T)
cond_d <- sample(0:1,replace = T)
df <- data.frame(id,gender,age,race,health_score,cond_a,cond_b,cond_c,cond_d)
regression_tables <- df %>% select(-id) %>%
gather(c(cond_a,cond_d),key = "condition",value = "case") %>%
group_by(condition) %>% nest() %>%
mutate(model = map(data,~glm(case ~ gender + age + race + health_score,family = "binomial",data = .)),table = map(model,~tbl_regression,exponentiate = T,conf.level = 0.99)) %>%
select(table) %>% unnest(table)
解决方法
问题似乎是使用 lambda 表达式 (~
) 而没有使用它,即指定参数。此外,没有可用的 tidy
方法(来自 broom
)从 tbl_regression
library(dplyr)
library(tidyr)
library(broom)
library(gtsummary)
out <- df %>%
select(-id) %>%
gather(c(cond_a,cond_b,cond_c,cond_d),key = "condition",value = "case") %>%
group_by(condition) %>%
nest() %>%
mutate(model = map(data,~glm(case ~ gender + age + race + health_score,family = "binomial",data = .)),table = map(model,tbl_regression,exponentiate = T,conf.level = 0.99)) %>%
select(table)
out$table[[1]]
除了 OP 使用 map
循环的方法,实际上我们可以简单地应用模型,tbl_regression
之后的 nest_by
(将 gather
替换为pivot_longer
因为 gather
会被弃用,pivot_longer
是一个通用版本)
out <- df %>%
select(-id) %>%
pivot_longer(cols = starts_with('cond'),names_to = 'condition',values_to = 'case') %>%
nest_by(condition) %>%
mutate(model = list(glm(case ~ gender + age +
race + health_score,data = data)),table_out = list(tbl_regression(model,exponentiate = TRUE,conf.level = 0.99)))
out
# A tibble: 4 x 4
# Rowwise: condition
# condition data model table_out
# <chr> <list<tbl_df[,5]>> <list> <list>
#1 cond_a [2,000 × 5] <glm> <tbl_rgrs>
#2 cond_b [2,000 × 5] <glm> <tbl_rgrs>
#3 cond_c [2,000 × 5] <glm> <tbl_rgrs>
#4 cond_d [2,000 × 5] <glm> <tbl_rgrs>
如果我们需要合并表,请在 tbl_merge
的 list
上应用 tbl_regression
tbl_merge(out$table_out)
-输出
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。