Search code examples
raggregatereshapegtsummary

How can I transpose a gtsummary tbl_summary object?


In my hypothetical scenario, 100 people are asked: What is your favorite color of car, shirt, and website (red, blue, or yellow)? This yields my mock data frame:

colors <- c("red", "blue", "yellow")
set.seed(42)
df <- data.frame(id = 1:100, 
car = sample(colors, 100, replace=TRUE), 
shirt = sample(colors, 100, replace=TRUE), 
website = sample(colors, 100, replace=TRUE)
)

I can make a nice summary table from gtsummary:

library(tidyverse)
library(gtsummary)

tbl_summary(df, include = c(car, shirt, website))

enter image description here

I would like to transpose this table data so the result has three rows (car, shirt, and website) and three columns (blue, red, and yellow), as in:

                # blue  red  yellow 
# Characteristic
car  39 (39%) 40 (40%) 21 (21%)
shirt 39 (39%) 35 (35%) 26 (26%)
website 35 (35%) 32 (32%) 33 (33%)

I tried a script which analyzes a continuous variable from: Transpose tbl_summary output but the result is not what I want.

map(
  c("car", "shirt", "website"),
  ~ tbl_summary(
    df,
    by = all_of(.x),
    include = c(car, shirt, website)
  )
) %>%
  tbl_stack()

enter image description here

Any advice? Thank you.


Solution

  • There is a function in the bstfun package that does just what you need, and it's a gtsummary extension. https://mskcc-epi-bio.github.io/bstfun/reference/tbl_likert.html

    colors <- c("red", "blue", "yellow")
    set.seed(42)
    df <- data.frame(
      id = 1:100, 
      car = sample(colors, 100, replace=TRUE), 
      shirt = sample(colors, 100, replace=TRUE), 
      website = sample(colors, 100, replace=TRUE)
    )
    
    df |> 
      bstfun::tbl_likert(include = c(car, shirt, website)) |> 
      gtsummary::as_kable() # convert to kable to display on SO
    
    Characteristic blue red yellow
    car 39 (39%) 40 (40%) 21 (21%)
    shirt 39 (39%) 35 (35%) 26 (26%)
    website 35 (35%) 32 (32%) 33 (33%)

    Created on 2023-12-10 with reprex v2.0.2