Search code examples
rr-markdowngtsummary

How to increase columns width in a gtsummary table in RMarkdown HTML file?


I'm working with gtsummary to create tables in RMarkdown HTML files. This is the code I'm using:

theme_gtsummary_language(
  language = "pt",
  decimal.mark = ",",
  big.mark = ".")

tab <- dados %>%
  select(anoobito, DESCRICAO.y) %>%
  tbl_summary(by = anoobito,
              label = c(DESCRICAO.y ~ "Causa Final")) %>%
  add_overall(last = T) %>%
  modify_table_body(fun = ~ dplyr::arrange(.x, desc(readr::parse_number(stat_0)))) %>%
  modify_spanning_header(c("stat_1":"stat_5") ~ "**Ano do Óbito**") %>%
  modify_header(label = "**Causa Final**",
                all_stat_cols() ~  "**{level}**<br>N = {n}") %>%
  bold_labels() %>%
  remove_row_type(type = "header") %>%
  modify_column_hide(columns = "stat_0")

tab$table_body <- head(tab$table_body, 10)

tab

I get the following result:

enter image description here

I was wondering if it's possible to increase columns width so "N =" appear under the years in a single row, just like the 2023 column.


Solution

  • One option would be to convert to a gt_tbl object using as_gt which allows to set the column width using gt::cols_width:

    • Default
    library(gtsummary)
    
    tab
    

    enter image description here

    • using gt::cols_width to increase the column width where I target the stat_x columns of the gtsummaty table using starts_with:
    library(gt)
    
    tab |> 
      as_gt() |> 
      gt::cols_width(starts_with("stat") ~ px(100))
    

    enter image description here

    DATA

    set.seed(123)
    
    dados <- data.frame(
      DESCRICAO.y = c(
        "arcu vitae potenti interdum imperdiet vestibulum suscipit fringilla nascetur tristique",
        "morbi nostra at curae purus venenatis sed nascetur scelerisque blandit"
      ),
      anoobito = sample(2019:2023, 5000, replace = TRUE, prob = c(.2, .3, .1, .2, .2))
    )