How to use latex math in Rmd to display properly on GitHub Pages

Working on our PH525x online course material, Rafa and I wanted to base all lecture material in Rmd files, as these are easy for students to load into RStudio to walk through the code. Additionally, the rendered markdown files can be displayed nicely on GitHub Pages (which uses Jekyll to turn markdown in HTML). All we needed to do is copy the markdown files into the /pages directory and they already look pretty great when viewed on (also we borrowed the theme from Karl Broman’s simple site template). By adding MathJax to the header of the GitHub Page template, we also render latex math formula from the original Rmd files.

Below I go over the issues we encountered with including math, but you can jump to the bottom if you just want our solution.


While RStudio would render latex math in the HTML preview using MathJax, we would run into problems when rendering the markdown with the Redcarpet markdown parser. For example:

in RStudio:


using the Redcarpet markdown parser with Jekyll:


What happened is that Redcarpet doesn’t recognize the `$` for the inline math, and it goes inside and sees the underscores, and adds italics to the text between them. I came up with some hacks for dealing with Redcarpet and latex math, but in the end, there was not a comprehensive solution to use Redcarpet with latex math.


We then tried out an alternate markdown parser called Kramdown. The Kramdown parser recognizes `$$` for inline or display math and won’t interpret symbols which are in between two `$$`. There are still some issues with trying to use `$` for inline math, for example:

in RStudio:


and the opposite effect using the Kramdown markdown parser with Jekyll:


But if we use `$$` for inline math, everything is fine in the rendered HTML from Jekyll.

The only remaining problem is that `$$` is recognized by RStudio as display math, so the helpful preview is no longer rendering nicely:


Our solution

We use the Kramdown parser with GitHub-flavored markdown to support the backtick fenced code blocks (see our config file):

markdown: kramdown

  input: GFM

We use `$` for display math in our Rmd files, and then we use a series of sed commands to convert `$` in the markdown files to `$$`. These md’s can be previewed locally with Jekyll and pushed to GitHub pages. It’s definitely a hack but it works.

Example Rmd

Example rendered HTML page


1 thought on “How to use latex math in Rmd to display properly on GitHub Pages”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s