gtsummary

Align Column Numbers by Decimal Mark in gtsummary Table


I am trying to create a table using the gtsummary package in R, with column numbers aligned by the decimal mark. Here's my code:

library(gtsummary)
library(gt)

theme_gtsummary_journal(journal = "jama")

gt::rx_adsl |>
  tbl_summary(
    include=c(SEX),
    by=TRTA,
    digits = all_categorical() ~ c(0, 1),
    missing = "no"
  )

This code produces the following table:

Code

How can I modify the table so that the numbers in the columns are aligned by the decimal mark?

I tried using gtsummary::modify_table_styling, but I couldn't achieve the desired alignment by the decimal mark.

Desired result:

Preview


Solution

  • There are three things you need to do to get the alignment you are after.

    1. Use formatting functions/rounding that include padding before the number to ensure all results are the same width. I am using the {cards} package for this, but you don't have to.
    2. Change the cell alignment from center to right.
    3. Use a fixed-width font for your table.

    Example below!

    library(gtsummary)
    packageVersion("gtsummary")
    #> [1] '1.7.2'
    
    
    # the cards pkg has functions that have fixed-width formatting (with space padding)
    # you don't need to use this package, however. It's not too much work to do it yourself
    packageVersion("cards")
    #> [1] '0.1.0'
    
    
    tbl <- gt::rx_adsl |>
      tbl_summary(
        include = SEX,
        by = TRTA,
        # use formatting/rounding functions that include padding
        digits = all_categorical() ~ list(cards::alias_as_fmt_fn("xx"), 
                                          cards::alias_as_fmt_fn("xx.x%")),
        missing = "no"
      ) |> 
      # change from center to right alignment
      modify_column_alignment(all_stat_cols(), "right") |> 
      as_gt() |> 
      # lastly, you need to use a fixed-width font to get proper alignment
      gt::opt_table_font(
        stack = "monospace-slab-serif"
      )
    #> 2 observations missing `TRTA` have been removed. To include these observations, use `forcats::fct_na_value_to_level()` on `TRTA` column before passing to `tbl_summary()`.
    

    enter image description here

    Created on 2024-05-16 with reprex v2.1.0