Search code examples
rgtsummary

Remove variable label when using tbl_strata() and tbl_summary() from gtsummary package


I would like to use tbl_summary() and tbl_strata() to create a summary table:

library(gtsummary)
library(ggplot2)

data("mpg")

mpg |> 
  select(hwy, cyl, manufacturer) |> 
  tbl_strata(strata = manufacturer, ~ .x |> 
               tbl_summary(by = cyl, type = list("hwy" ~ "continuous")),
             .combine_with = "tbl_stack")

enter image description here

But I would like to omit the "hwy" label and just use "manufacturer" as label, in order to get rid of the many blank rows. Is that possible?


Solution

  • This is very similar to the second example in the help file for ?tbl_strata.

    • You will want to use .combine_args = list(group_header = NULL) to suppress the default stacked headers.
    • Update to tbl_strata2() which passes the strata level as a second argument, and add this line to update the label label = list(hwy = .y)
    library(gtsummary)
    packageVersion("gtsummary")
    #> [1] '1.7.2'
    
    data("mpg", package = "ggplot2")
    
    mpg |>
      select(hwy, cyl, manufacturer) |>
      tbl_strata2(
        strata = manufacturer,
        ~ .x |>
          tbl_summary(
            by = cyl,
            type = list(hwy = "continuous"),
            label = list(hwy = .y)
          ),
        .combine_with = "tbl_stack",
        .combine_args = list(group_header = NULL)
      ) |> 
      as_kable() # convert to kable to display on SO
    #> ℹ Column headers among stacked tables differ. Headers from the first table are
    #> used. Use `quiet = TRUE` to suppress this message.
    
    Characteristic 4, N = 8 6, N = 9 8, N = 1
    audi 29 (27, 29) 25 (25, 26) 23 (23, 23)
    chevrolet 29 (28, 29) 26 (26, 28) 20 (17, 24)
    dodge 24 (24, 24) 22 (18, 23) 16 (15, 17)
    ford 19 (17, 25) 17 (17, 21)
    honda 32 (32, 34)
    hyundai 28 (27, 29) 25 (24, 26)
    jeep 20 (20, 21) 17 (14, 18)
    land rover 17 (15, 18)
    lincoln 17 (17, 18)
    mercury 18 (18, 19) 18 (18, 19)
    nissan 30 (29, 31) 25 (19, 26) 18 (18, 18)
    pontiac 27 (26, 27) 25 (25, 25)
    subaru 26 (25, 26)
    toyota 30 (23, 31) 20 (19, 26) 17 (16, 18)
    volkswagen 29 (29, 29) 29 (29, 29) 25 (24, 26)

    Created on 2024-04-12 with reprex v2.1.0