Search code examples
rlatexdt

Rendering math symbols in datatable


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"
  )

Solution

  • Then you might build a katex_htmls() that replaces the tex from between each $ with a translation to "katex html":

    library(dplyr)
    library(DT)
    library(katex)
    library(purrr)
    library(stringr)
    
    # 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
        )
      })
    }
    
    # katex_html_vec() to process 0 or more $tex$s per string
    katex_htmls <- function(
        x,
        displayMode = FALSE, 
        ..., 
        include_css = TRUE, 
        preview = FALSE
      ) {
      purrr::map_chr(x, ~ {
        stringr::str_replace_all(.x, "\\$.*?\\$", function(m) {
          m %>% 
            stringr::str_remove_all("\\$") %>% 
            katex_html_vec(
              displayMode = displayMode, 
              ..., 
              include_css = include_css, 
              preview = preview
            )
        })
      })
    }
    
    data.frame(
      var1 = c("A", "B"),
      var2 = c("this string contains $\\alpha$", "this one $\\beta$")
    ) %>% 
      mutate(var2 = katex_htmls(var2)) %>% 
      datatable(
        rownames = FALSE,
        colnames = c("Col1", "Col2"), 
        filter = "top",
        escape = FALSE
      )
    

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