Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 584
Marco B Avatar asked Oct 15 '25 05:10

Marco B


1 Answers

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

like image 155
Daniel D. Sjoberg Avatar answered Oct 16 '25 17:10

Daniel D. Sjoberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!