"Erroneous nesting of equation structures" in using "\begin{align}" in a multi-line equation in rmarkdown to knit+pandoc pdf

Hernando Casas picture Hernando Casas · Sep 26, 2014 · Viewed 14.7k times · Source

I am writing some multi-line equations in R Markdown - LaTeX, using auto-numbering and \begin{align}. Here's a working the example:

---
title: "test"
output: html_document
---

(@eq01) $$
\begin{align}
y = x^2 \\
y = x^3 \\
y = \sqrt[2]{x}
\end{align}
$$

This works great when the output is html_document. Here's the result:

html_doc

But when I change the output document to pdf:

output: pdf_document

I get the following error (I am using RStudio latest Version 0.98.1056):

error

I've been trying to read the documentation as suggested in the error message, but I do not seem to get a handle on it. I've checked Stack Overflow and Google and although there are some related posts/questions (for example here, here, here), none of them solve the problem (or apply to my problem).

I've also tried to tweak everything. The most evident solution would be to get rid of the \begin{align} environment,

(@eq01) $$
y = x^2 \\
y = x^3 \\
y = \sqrt[2]{x}
$$

but it does not work for two reasons. First, the html version does not work as nicely because the auto-numbering does not appear centered in the multi-line equation, but rather on the first line (and I don't like it like that).

html output without the begin align

Second, although the pdf version in this case does compile and produce the pdf, it does not recognize that it is a multi-line equation (it's like it does not recognize the new line command \).

pdf

Any ideas are really appreciated. I've been struggling with this for a while and I cannot find a solution. I kinda love R Markdown because it really integrates the analysis with writing and communicating in a single tool (rather than using many different tools going back and forth). However, it seems there is still a long way to go before we can write one single source file and that it renders appropriately in several different output formats.

Answer

Tyr Wiesner-Hanks picture Tyr Wiesner-Hanks · Oct 2, 2014

I was receiving the same error when trying to send an aligned block to PDF. Try changing the following:

$$
\begin{align}
y = x^2 \\
y = x^3 \\
y = \sqrt[2]{x}
\end{align}
$$

to the following:

$$
\begin{aligned}
y = x^2 \\
y = x^3 \\
y = \sqrt[2]{x}
\end{aligned}
$$

\begin{align} is a self-contained math environment, whereas \begin{aligned} needs to be placed inside an existing math environment. Since Rmd delineates math sections with $$...$$, it seems like \begin{align} was trying to start a second math environment within the first and causing problems.