Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering math symbols in datatable

Tags:

r

latex

dt

How can I pass latex symbol code to a datatable in R? I found this post, but I don't know JS and have no idea how to implement something like this in R.

[Edit] I have also tried the LaTeX solution from this post but got a blank table in return.

MWE

library(DT)

df <- data.frame(var1 = c("A", "B"),
                 var2 = c("this string contains $\\alpha$", "this one $\\beta$"))

df %>%
  datatable(
    rownames = FALSE, escape = TRUE,
    colnames = c("Col1", "Col2"), 
    filter = "top"
  )
like image 490
Robin Donatello Avatar asked Dec 06 '25 16:12

Robin Donatello


1 Answers

You could use the {katex} package like so:

library(dplyr)
library(DT)
library(katex)
library(purrr)

# vectorized katex_html() with sensible settings for non-interactive use
katex_html_vec <- function(
    tex, 
    displayMode = FALSE, 
    ..., 
    include_css = TRUE, 
    preview = FALSE
  ) {
  purrr::map_chr(tex, ~ {
    katex::katex_html(
      .x, 
      displayMode = displayMode,
      ..., 
      include_css = include_css, 
      preview = preview
    )
  })
}

data.frame(
  var1 = c("A", "B"),
  var2 = c("\\alpha", "\\beta")
) %>%
  mutate(var2 = katex_html_vec(var2)) %>%
  datatable(
    rownames = FALSE,
    colnames = c("Col1", "Col2"), 
    filter = "top",
    escape = FALSE
  )

Created on 2024-04-19 with reprex v2.1.0

like image 76
the-mad-statter Avatar answered Dec 09 '25 17:12

the-mad-statter



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!