LaTeX

Within R markdown (within RStudio), we can use the LaTeX language to create beautiful mathematical equations. Here are some examples to work through.


The helpful $ and $$
If I type $f_X(x)$ in a body of text, it produces \(f_X(x)\). Notice that this LaTeX text is started by $ and ended by $. With just 1 $ on either end, the formula remains in my body of text. If I want it to appear on its own in the center of the page I use $$ on either end. For example, $$f_X(x)$$ gives \[f_X(x)\]


Basic features

  • probability & counting stuff

    code result
    $P(A)$ \(P(A)\)
    $P(A \cap B)$ \(P(A \cap B)\)
    $P(A \cup B)$ \(P(A \cup B)\)
    $P(A|B)$ \(P(A|B)\)
    ${n \choose x}$ \({n \choose x}\)
  • subscripts

    code result
    $x_2$ \(x_2\)
    $x_10$ \(x_10\)
    $x_{10}$ \(x_{10}\)
  • superscripts

    code result
    $x^2$ \(x^2\)
    $x^10$ \(x^10\)
    $x^{10}$ \(x^{10}\)
  • fractions

    code result
    $\frac{1}{2}$ \(\frac{1}{2}\)
    $\frac{a+1}{b+0}$ \(\frac{a+1}{b+0}\)
  • integrals

    code result
    $\int f(x) dx$ \(\int f(x) dx\)
    $\int_0^1 f(x) dx$ \(\int_0^1 f(x) dx\)
    $\int_{-1}^{10} f(x) dx$ \(\int_{-1}^{10} f(x) dx\)
    $\int_{-\infty}^\infty f(x) dx$ \(\int_{-\infty}^\infty f(x) dx\)


Multi-line equations

One of many ways to present a multi-line equations is by using split. In the examples below, notice the following:

  • start with \begin{split} and end with \end{split}
  • indicate the end of each line in the equation by \\
  • use & to indicate the point at which to line up the lines


This code

$$\begin{split}
x & = 1 \\
y & = 2 \\
\end{split}$$

produces

\[\begin{split} x & = 1 \\ y & = 2 \\ \end{split}\]

This code

$$\begin{split}
P(A|B) & = \frac{P(A \cap B)}{P(B)} \\
       & = \frac{P(B|A)P(A)}{P(B)} \\
\end{split}$$

produces

\[\begin{split} P(A|B) & = \frac{P(A \cap B)}{P(B)} \\ & = \frac{P(B|A)P(A)}{P(B)} \\ \end{split}\]

“Cases” are special type of multi-line equation:

$$f(x) = \begin{cases}
 0.2 & x = 1 \\
 0.8 & x = 2 \\
\end{cases}$$

produces

\[f(x) = \begin{cases} 0.2 & x = 1 \\ 0.8 & x = 2 \\ \end{cases}\]