Search code examples
rlatexr-markdownrstudiomathjax

R Markdown equation preview for \newcommand


I have an R markdown file with several custom latex commands, defined via \newcommand. I really like the preview in RStudio, but it doesn't seem to be able to render these commands or those imported from packages. In the following example, neither the custom command \expect nor the package command \bm is shown in the preview. Instead, they are shown in red letters in the preview.

Is there any way to have them rendered in the preview?

---
header-includes:
   - \usepackage{bm}
output:
    pdf_document
---

\newcommand{\expect}[1]{\mathbb{E}\left[ #1 \right]}

$$
\expect{\bm{X}} = \lambda
$$

Solution

  • The preview in RStudio IDE will render the equation using Mathjax.

    Defining commands in math mode

    Mathjax supports \newcommand, but you need to define it inside a math environment for it to be processed in the preview, like this:

    ---
    title: "My maths"
    output: html_document
    ---
    
    $$
    \newcommand{\e}{\mathcal{E}}
    \e
    $$
    

    RStudio displaying the math correctly

    Using math mode conditionally

    For pdfs, however, LaTeX does not recognize \newcommand in math mode, which will lead to an "Undefined control sequence" error. To fix this, we need to trick rmarkdown to use math mode when we're working with html output (and want to see the previews), but exit out of math mode if the document is transpiled to a .tex document.

    ---
    title: "My maths"
    output: pdf_document
    ---
    
    $$`r if(!knitr::is_html_output()) ' \\]'`
    \newcommand{\e}{\mathcal{E}}
    `r if(!knitr::is_html_output()) '\\[ '`$$
    
    $$
    \e
    $$
    

    Now, the html output contains node elements which are interpreted by Mathjax, whereas the .tex output looks like this:

    % ...
    \[ \]
    \newcommand{\e}{\mathbb{E}}
    \[ \]
    
    \[
    \e
    \]
    % ...
    

    Using bm

    In your case you are trying to use bm which is not supported by Mathjax. See https://github.com/mathjax/MathJax/issues/1219

    As a workaround, they suggest using boldsymbol. To make sure that boldsymbol is only used for the html, we can do the following:

    $$`r if(!knitr::is_html_output()) ' \\]'`
    \newcommand{\expect}[1]{\mathbb{E}\left[ #1 \right]}
    `r if(!knitr::is_html_output()) ' % '`\newcommand{\bm}[1]{\boldsymbol{#1}}
    `r if(!knitr::is_html_output()) ' \\['`$$
    
    $$
    \expect{\bm{X}} = \lambda
    $$
    

    Now, the \bm command will be redefined when working with Mathjax, but \newcommand{\bm} will be commented out with the %-sign when a pdf is generated.