微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 gtsummary 中因变量的值命名模型

如何解决使用 gtsummary 中因变量的值命名模型

我有一个包含 14 个因变量的列表,我正在为其运行相同的回归模型(相同的模型类型,相同的自变量)。我使用 gather 将所有因变量作为单个 outcome 变量,在该变量上运行 tbl_uvregressiontbl_regression,然后使用 tbl_stackgtsummary 包来组织输出。我想弄清楚如何使用每个模型的 outcome 变量的值来命名每个表。我知道我可以将名称列表传递给 tbl_stack(group_header),但我注意到这很容易出错,因为我必须小心 outcome 变量中的值的排列方式,然后确保我以相同的顺序输入它们,我犯了足够多的错误,以至于我担心这种方法。有没有办法直接从因变量的值中获取 group_header 参数?结果变量已命名,但当我收集它们以运行模型时,当然不会保留这些变量。

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 = "outcome",value = "case") %>% 
  group_by(outcome) %>% 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)) %>% 
pull(table) %>% tbl_stack(**[model names to become table headers]**)

在这个例子中,我想要堆叠表格,其中每个表格的标题是“条件 A”、“条件 B”、“条件 C”、“条件 D”(gathered 结果的值多变的)。两列标题(下面示例屏幕截图中的“成人”和“儿童”)将来自为成人和儿童分别运行模型,按上述方式堆叠它们,然后使用 tbl_merge

Example of final output

解决方法

我无法运行帖子中的代码,此 table = map(model,~ .. 部分会抛出一些奇怪的输出。

如果您查看拉取前的 tibble,请使用以下代码:

regression_tables <- df %>% select(-id) %>% 
gather(c(cond_a,cond_b,cond_c,cond_d),key = "outcome",value = "case") %>% 
group_by(outcome) %>% 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))

您看到有一个对应的列 outcome 嵌套您的结果:

# A tibble: 4 x 4
# Groups:   outcome [4]
  outcome data                 model  table     
  <chr>   <list>               <list> <list>    
1 cond_a  <tibble [2,000 × 5]> <glm>  <tbl_rgrs>
2 cond_b  <tibble [2,000 × 5]> <glm>  <tbl_rgrs>
3 cond_c  <tibble [2,000 × 5]> <glm>  <tbl_rgrs>
4 cond_d  <tibble [2,000 × 5]> <glm>  <tbl_rgrs>

我们可以像这样堆叠它:

tbl_stack(regression_tables$table,group_header=regression_tables$outcome)

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。