Search code examples
rr-markdowngtsummarygt

R: Markdown or HTML markup in `gtsummary` tables


I have a table with variable names usually spelt with superscript or subscript numbers. I'm using R package {gtsummary} to automatically create the table from select columns of a data frame/tibble.

Say this is the tibble:

library(nycflights13)

lm_1 <- lm(arr_delay ~ air_time, flights)

tbl_1 <- tbl_regression(lm_1, exponentiate = F,
                        label = list(
                            air_time ~ "Air Time"
                        )) %>% 
    add_glance_source_note(include = c('r.squared'))

tbl_1

… but I need to write this as Airtime (HTML Air<sup>time</sup> or Markdown Air~time~).

In {gtsummary}, specifying the label argument in HTML or Markdown doesn't work for me:

tbl_1 <- tbl_regression(lm_1, exponentiate = F,
                        label = list(
                            air_time ~ "Air<sup>time</sup>",
                            sched_dep_time ~ "Departure^time^"
                        )) %>% 
    add_glance_source_note(include = c('r.squared'))

Table: not working for me

I've tried wrapping the strings in gt::html() or gt::md() but it didn't change anything:

tbl_1 <- tbl_regression(lm_1, exponentiate = F,
                        label = list(
                            air_time ~ html("Air<sup>time</sup>"),
                            sched_dep_time ~ md("Departure^time^")
                        )) %>% 
    add_glance_source_note(include = c('r.squared'))

Would it be possible to use HTML and/or Markdown in gtsummary tables? Thanks!


Solution

  • To 100% honest, I don't know why this solution works...but it does! The {gt} package has a function called fmt_markdown() that is meant to convert markdown syntax to the specified output type. BUT in your example, the markdown superscript is not recognized (more on why here https://github.com/rstudio/gt/issues/129#issuecomment-663753251). BUUUUT, when I apply that function to your HTML tag superscripts, they are recognized and you get the output you're looking for.

    library(gtsummary)
    library(nycflights13)
    
    lm_1 <- lm(arr_delay ~ air_time + sched_dep_time , flights)
    
    tbl_regression(lm_1, 
                   label = list(air_time ~ "Air<sup>time</sup>",
                                sched_dep_time ~ "Departure<sup>time</sup>")) %>% 
      add_glance_source_note(include = 'r.squared') %>%
      as_gt() %>%
      gt::fmt_markdown(columns = vars(label))
    

    enter image description here