Search code examples
r-markdownknitrxaringan

Rmarkdown rendering error in math with underscores


I am trying to display a formula in RMarkdown with two underscores (one inside a {}-bracket). The preview in Rstudio works as expected and the formula is rendered correctly. In the rendered document (HTML), the code is, however, not rendered correctly but instead the parts of the equation between the underscores are put into italics as if they were normal text and not within a formula environment.

An MWE is given by this

$$
w = \frac{1}{x_1}\sum y_{1} 
$$

which gets rendered to this

enter image description here

We see that the parts between the underscores are displayed in italic and the formula is not rendered but its source code is displayed.

A solution is to escape the underscores (breaks the preview, but gets rendered correctly)

$$
w = \frac{1}{x\_1}\sum y\_{1} 
$$

Note that only escaping one underscore works as well!

Is this expected behavior or a bug in the knitr engine?

Is there a solution that solves this in both the preview as well as the final document?

Edit

I use xaringan and xaringanthemer, not sure if this causes the error. Nonetheless, here is my header

title: "MWE"
output:
  xaringan::moon_reader:
    lib_dir: libs
    css: xaringan-themer.css
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false

Solution

  • The solution can be found in the official documentation:

    Limitations:

    1) The source code of a LaTeX math expression must be in one line, unless it is inside a pair of double dollar signs, in which case the starting $$ must appear in the very beginning of a line, followed immediately by a non-space character, and the ending $$ must be at the end of a line, led by a non-space character;

    There should not be spaces after the opening $ or before the closing $.

    Math does not work on the title slide (see #61 for a workaround).

    So, just write:

    $$w = \frac{1}{x_1}\sum y_{1}$$