Mathematical units in gt table with Rmarkdown

Viewed 226

I have this dataframe:

df = data.frame(a = c("$B_{a}$", "$m^{a}$"))

When I make a table using kable in Rmarkdown like so:

df %>% knitr::kable()

and knit it to a pdf_document, I get this:

enter image description here

which is what I expected.

Now, I want to reproduce the same table, but using the package gt. When I do:

library(gt)
df %>% gt()

I get this:

enter image description here

What else do I have to do that so that gt table "understands" these are mathematical notations?

1 Answers

The <sub></sub> and <sup></sup> works with gt. One option is to replace the characters in the original dataset column with html syntax using str_remove/str_replace from stringr

library(gt)
library(stringr)
library(dplyr)
df %>%
    mutate(a = str_remove_all(a, "[{}$]") %>% 
         str_replace_all( c('(.)_(.)', "(.)\\^(.)"),
           c("\\1<sub>\\2</sub>", "\\1<sup>\\2</sup>"))) %>%
     gt() %>%
     fmt_markdown(columns = everything())

-output

enter image description here

Related