MathJax is not rendering properly within kableExtra tables in Quarto, most of the time emanating from how HTML escapes LaTeX expressions in table cells. Quarto could even take these formulas like ordinary text and not MathJax expressions. Here are a few possible reasons and solutions:
Possible reasons for why MathJax does not render:
Quarto Escapes HTML by Default:
Quarto usually escapes the special characters inside the kableExtra tables, and therefore, MathJax could not process those.
Need Explicit $$ or \( \) Wrapping for MathJax:
If cells in the table do not define inline or block delimiters for any formulas, MathJax will ignore them.
Missing HTML Dependencies Include:
If MathJax is not properly included, it won't render LaTeX within the tables.
Rendering Format Conflict (HTML vs PDF vs Markdown):
There is a requirement for different handling in the case of some rendering formats, like PDF with LaTeX, which should be different from HTML.
Solutions to Ensure that MathJax Renders in kableExtra Tables
1. Disable HTML escaping in kableExtra: with escape = FALSE
Disable HTML Escaping in kableExtra: With escape = FALSE. That would ensure that LaTeX is interpreted:
library(kableExtra)
df <- data.frame(
Variable = c("x", "y"),
Formula = c("$x^2 + y^2$", "$\\frac{a}{b} + c$")
)
kable(df, escape = FALSE) %>%
kable_styling()
2. Use Proper MathJax Delimiters
Ensure equations are wrapped with:
- Inline math: \( x^2 + y^2 \)
- Block math: $$ x^2 + y^2 $$
Example in kableExtra:
df <- data.frame(
Formula = c("\\( x^2 + y^2 \\)", "$$\\frac{a}{b} + c$$")
)
kable(df, escape = FALSE)
3. Explicitly Load MathJax in Quarto
In your Quarto YAML header, include:
format:
html:
include-in-header:
text: |
<script type="text/javascript">
MathJax = {
tex: { inlineMath: [['$', '$'], ['\\(', '\\)']] }
};
</script>
This ensures MathJax loads correctly in the HTML output.
4. Use as_is from knitr
For better LaTeX handling within Quarto + kableExtra, you can use knitr::asis_output():
df$Formula <- knitr::asis_output(df$Formula)
This prevents unwanted escaping in HTML reports.
Final Thoughts
The best approach depends on your output format (HTML, PDF, Word). If rendering for HTML, use escape = FALSE with properly formatted MathJax syntax. If outputting to PDF via LaTeX, ensure kableExtra correctly integrates with LaTeX equations