R gtsummary tbl_summary 包含分层和两个独立分组变量

问题描述 投票:0回答:1

我正在尝试创建一个具有分层类别的

tbl_summary
,并且在每个分层类别中都有两个单独的分类(可能是二进制)变量。下面是我希望如何布局表格的示例,但是,
d
的 n/% 是占位符,与我的示例数据集不符。

example table structure

我不想组合变量

b
c
,因为这些是每个观察的不同且独立的变量。我尝试使用
tbl_summary
tbl_strata
tbl_merge
的组合来实现我想要的表结构,但是我无法使其正常工作。

这是我的最小示例(

R v4.2.2
):

library(readr)
library(dplyr)
library(tidyverse)
library(gtsummary)

df <- data.frame(id=1:10,
                 a=c('red', 'blue', 'red', 'red', 'blue', 'red', 'blue', 'blue', 'blue', 'red'),
                 b=c('yes', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes', 'yes', 'no'),
                 c=c('cheese', 'cheese', 'steak', 'steak', 'cheese', 'steak', 'steak', 'cheese', 'steak', 'steak'),
                 d=c(22, 82, 44, 56, 27, 61, 22, 19, 38, 47)
)

df$a <- factor(df$a)
df$b <- factor(df$b)
df$c <- factor(df$c)
df$d <- factor(df$d)

t1 <- df %>%
   select(a, b, d) %>%
   mutate(a = paste("a=", a)) %>%
   mutate(b = paste("b=", b)) %>%
   tbl_strata(
      strata = a,
      .tbl_fun =
         ~ .x %>%
         tbl_summary(by = b, missing = "no"),
      .header = "**{strata}**, N = {n}"
   )

t2 <- df %>%
   select(a, c, d) %>%
   mutate(a = paste("a=", a)) %>%
   mutate(c = paste("c=", c)) %>%
   tbl_strata(
      strata = a,
      .tbl_fun =
         ~ .x %>%
         tbl_summary(by = c, missing = "no"),
      .header = "**{strata}**, N = {n}"
   )

tbl_merge(
   tbls = list(t1, t2),
   tab_spanner = c("**b**", "**c**")
)

此代码生成此表,该表没有

b
c
的正确列,并且缺少总体分层变量
a

code output

r gtsummary
1个回答
0
投票

我可能已经修好了。

df <- data.frame(id=1:11,
                 a=c('red', 'blue', 'red', 'red', 'blue', 'red', 'blue', 'blue', 'blue', 'red', 'blue'),
                 b=c('yes', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes', 'yes', 'no', 'no'),
                 x=c('cheese', 'cheese', 'steak', 'steak', 'cheese', 'steak', 'steak', 'cheese', 'steak', 'steak', 'cheese'),
                 d=c(22, 82, 44, 56, 27, 61, 22, 19, 38, 47, 38)
)

df$a <- factor(df$a)
df$b <- factor(df$b)
df$x <- factor(df$x)
df$d <- factor(df$d)

t3 <- df %>%
   select(b, d) %>%
   mutate(b = paste("b=", b)) %>%
   tbl_summary(by = b, 
               missing = "no"
   )

t4 <- df %>%
   select(x, d) %>%
   mutate(x = paste("x=", x)) %>%
   tbl_summary(by = x, 
               missing = "no"
   )

df %>% tbl_strata(
   strata = a,
   .tbl_fun =
      ~tbl_merge(
         tbls = list(t3, t4)
      ),
   .header = "**a={strata}**, N = {n}"
)

我将每个表中的

tbl_strata
移至合并版本上,并将
tbl_merge
(不是
~ .x %>%
)传递给
tbl_strata

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.