Search code examples
gtsummary

Is it possible to transpose tbl_summary table (Pivot table)


I would want to create a pivot table using the dataframe using tbl_summary

head(tblbdcc)
# A tibble: 6 x 11
  ntdcc    miphlycc anopmcrpcc anomcrtcc cleftscc impanuscc hypcc talipcc limbcc omphcc gascc
  <fct>    <fct>     <dbl+lbl> <fct>     <fct>    <fct>     <fct> <fct>   <fct>  <fct>  <fct>
1 Cases    NA               NA NA        NA       NA        NA    NA      NA     NA     NA   
2 NA       Cases            NA NA        NA       NA        NA    NA      NA     NA     NA   
3 Controls NA               NA NA        NA       NA        NA    NA      NA     NA     NA   
4 Controls NA               NA NA        NA       NA        NA    NA      NA     NA     NA   
5 Controls NA               NA NA        NA       NA        NA    NA      NA     NA     NA   
6 NA       NA               NA NA        NA       NA        Cases NA      NA     NA     NA

tblbdscc <- tblbdcc %>%
     tbl_summary( 
      missing = "no",
      statistic = all_categorical() ~ "{n}"
)

I would want to transform the table from enter image description here

to

enter image description here


Solution

  • There is no pivot table in gtsummary, but you can construct the table one row at a time and stack the resulting tables. Example below.

    library(gtsummary)
    library(tidyverse)
    #> Warning: package 'readr' was built under R version 4.1.2
    packageVersion("gtsummary")
    #> [1] '1.5.0'
    set.seed(11234)
    
    # simulate data
    df <- 
      tibble(
        ntdcc = sample(c("Case", "Control", NA), 20, replace = TRUE),
        gascc = sample(c("Case", "Control", NA), 20, replace = TRUE),
        limbcc = sample(c("Case", "Control", NA), 20, replace = TRUE)
      )
    
    # loop over every column in df to construct table
    tbl <- 
      names(df) %>%
      map(
        # build summary table for single category
        ~ df %>%
          select(all_of(.x)) %>%
          mutate(..true.. = TRUE) %>%
          filter(complete.cases(.)) %>%
          tbl_summary(
            by = all_of(.x),
            missing = "no",
            statistic = ~"{n}", 
            label = list(..true.. = .x)
          ) %>%
          # update column headers
          modify_header(
            all_stat_cols() ~ "**{level}**",
            label = "**Category Assigned**"
          )
      ) %>%
      # stack all tbls together
      tbl_stack() %>%
      # remove all footnotes
      modify_footnote(all_stat_cols() ~ NA)
    

    enter image description here Created on 2022-01-19 by the reprex package (v2.0.1)