Tuesday, July 13, 2021 From rOpenSci (https://ropensci.org/blog/2021/07/13/katex-release/). Except where otherwise noted, content on this site is licensed under the CC-BY license.
A new rOpenSci package katex is now on CRAN. This package allows for converting latex math expressions to HTML and MathML for use in markdown documents or package documentation.
An alternative solution is to perform the rendering when you generate the html page, and embed the pre-generated html snippet directly in the document. This makes the html file slightly larger, but the page loads much faster and is more robust because we do not need a complex dependency on the client. This is often called “server-side”, because usually html is generated by a web server.
The new katex package provides server-side math rendering in R. It can be used to include math when generating html in R (e.g. via Rmarkdown or R package documentation) without having to include MathJax in the output html document.
katex_mathml() render a string with math to a html and mathml string. The html output has an option
preview which will show a preview of the generated HTML snippet directly in a browser or the RStudio viewer.
# Basic example: render and show math html
math <- example_math()
html <- katex_html(math, preview = TRUE)
# Convert to mathml
mathml <- katex_mathml(math)
Note that by default, katex_html actually returns a mix of HTML for visual rendering and includes MathML for accessibility. The katex docs site has more detailed information and additional options. Hopefully this can be used to enable support for server-side math in knitr/rmarkdown soon!
The katex package also has a powerful helper function
math_to_rd to insert math into R documentation (
.rd) files. This uses Katex rendering for R documentation rendered in html format, and the appropriate latex macros for documentation rendered in pdf or plain-text.
You can call this directly from within your roxygen2 or Rd files using the
\Sexpr macro like this:
Check out the
?math_to_rd manual page in R or the math_to_rd docs for live examples and more details.