KirkD-CO
KirkD-CO

Reputation: 1793

Making pretty equations in RMarkdown with LaTeX

I'm trying to create nicely formatted equations in RMarkdown, but I cannot seem to get it to Knit without errors. The LaTeX chunk I have looks like this:

---
title: "Untitled"
author: "KirkD-CO"
date: "September 18, 2019"
output: pdf_document
---

$$
f(x) = \beta_0 + \beta_1 x + \beta_2 x^2 + \beta_3 x^3 + \beta_4 (x-\xi)^3_+
\\
\begin{equation}
  (x-\xi)^3_+ =
    \begin{cases}
      (x-\xi)^3 \ , \  x>\xi
      \\
      0 \ \ \ \ \ \ \ \ \ \ \ \ \ , \ x\leq\xi
    \end{cases}       
\end{equation}
\\ 
\
\\
\begin{aligned}
  (x \leq \xi) \Rightarrow f(x) &= \beta_0 + \beta_1 x + \beta_2 x^2 + \beta_3 x^3
  \\
  (x > \xi) \Rightarrow f(x) &= \beta_0 + \beta_1 x + \beta_2 x^2 + \beta_3 x^3 + \beta_4(x^3 -3x^2\xi + 3x\xi^2 - \xi^3)
  \\
  &=(\beta_0 + \beta_4\xi^3) + (\beta_1 + 3\beta_4\xi^2)x + (\beta_2 - 3\beta_4)
\end{aligned}
$$

And in RStudio I see this:

enter image description here

But when I try to Knit it, I get this error:

! LaTeX Error: Bad math environment delimiter.

I've search Google and StackOverflow and found many similar problems with answers suggesting using [ ] instead of \begin{equation}, other suggest using only one $ instead of $$, and still others refer to a variety of LaTeX packages, a few of which I've tried and wound up in installation purgatory.

Any suggestion on a straight forward way to get Kniter to Knit a PDF with the output RStudio displays?

EDIT: I'm using R 3.5.3 and Kniter 1.22 on Fedora 30.

EDIT2: Under Tools -> Global Options -> Sweave -> Typeset LaTeX into PDF using: is set to pdfLaTeX

Upvotes: 9

Views: 14849

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50738

Following up from the comments, here is a cleaned version:

---
title: "Untitled"
author: "KirkD-CO"
date: "September 18, 2019"
output: pdf_document
---

$$
f(x) = \beta_0 + \beta_1 x + \beta_2 x^2 + \beta_3 x^3 + \beta_4 (x-\xi)^3_+
$$

$$
(x-\xi)^3_+ =
\begin{cases}
 (x-\xi)^3\, ,& x>\xi \\
 0  ,& x\leq\xi
 \end{cases}       
$$

$$
\begin{aligned}
  (x \leq \xi) \Rightarrow f(x) &= \beta_0 + \beta_1 x + \beta_2 x^2 + \beta_3 x^3 \\
  (x > \xi) \Rightarrow f(x) &= \beta_0 + \beta_1 x + \beta_2 x^2 + \beta_3 x^3 + \beta_4(x^3 -3x^2\xi + 3x\xi^2 - \xi^3) \\
  &=(\beta_0 + \beta_4\xi^3) + (\beta_1 + 3\beta_4\xi^2)x + (\beta_2 - 3\beta_4)
\end{aligned}
$$

Producing

enter image description here

Some specific comments:

  1. Put separate LaTeX math mode chunks into separate $$ ... $$ (or \[ ... \] environments (unless you use a multi-line math environment, see below).
  2. Inside a cases environment, use & for horizontal alignment of different parts in every case
  3. Don't use \\ unless you're using some multi-line math environment (like cases, aligned); conversely, if you do use a multi-line math environment, you must separate lines with \\.

Upvotes: 14

Related Questions