Combining tbl_strata summary tables in R

195 views Asked by At

I want to combine three table strata table summary objects. You can't merge them with the tbl_merge function. What can I do?

I have three tables like this:

table_one <- data %>%
  select(Var1m, Var2, Var3, Var4, Var5, Var6, Var7) %>% 
  tbl_strata(
    strata = Var7,
    .tbl_fun =
      ~ .x %>%
      tbl_summary(by = Var6, missing = "no") %>%
      add_p(),
    .header = "**{strata}**, N = {n}"
  ) 

The library is the gt_summary library. The goal is to have all Characteristics for the variables once on the left and then table one with the two groups, table two with the two groups and three with the groups next to each other in one table. Here ist a pictore of what I'm trying to achieve:

see picture of summary table below (my tables will be based on three different data sets (same format but different number of cases)

I'm not sure what I'm missing. I tried the svryr library combine() function, transforming the tables into dfs and then combining.. combining by bind_rows

Any help is greatly appreciated!

1

There are 1 answers

0
jsavn On

If I understand your question correctly, you are attempting to use two levels of stratification. The example you posted uses one level only, by Grade (I, II, & III). I think tbl_strata only supports one level, so you'll need to structure your data accordingly.

One thing you could try is to merge the data used for table_one with the data used for the (I'm assuming from your example) table_two and table_three. From your example, it looks like you're using Var7 to stratify data, so I'll assume table_two and table_three contain Var8 and Var9, respectively. Using pivot_longer, for example, you can merge all three of these into a single variable, which you then pass to tbl_strata as your stratification variable.

library(tidyverse)
library(gtsummary)

merged_data <- bind_rows(  # this will depend on your data so it might not be as simple as here...
 data,
 data_for_table_two,
 data_for_table_three
) %>%
pivot_longer(cols = c(Var7, Var8, Var9))

table_merged <- merged_data %>%
  select(Var1m, Var2, Var3, Var4, Var5, Var6, Var789) %>% 
  tbl_strata(
    strata = Var789,
    .tbl_fun =
      ~ .x %>%
      tbl_summary(by = Var6, missing = "no") %>%
      add_p(),
    .header = "**{strata}**, N = {n}"
  )