Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical units in gt table with Rmarkdown

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?

like image 792
bird Avatar asked Jan 25 '26 07:01

bird


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

like image 146
akrun Avatar answered Jan 27 '26 23:01

akrun



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!