Search code examples
r-markdownbookdown

Adding chapter numbers to equation numbers in r markdown


I want to number equations in a document created using r markdown, output to pdf but I want to include the chapter number in the equation numbering.

I have followed the instructions as shown in https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html#equations

The labels in the link include the chapter number but mine don't.

---
number_sections: true
fig_caption: yes
title: "Test equation nos"
output: 
  bookdown::pdf_document2: default
---

# Chapter 1

I would like this equation to be numbered (1.1) but it is just labelled (1)

\begin{equation}
  e = mc^2
  (\#eq:emc)
\end{equation}

# Chapter 2

I would like this equation to be numbered (2.1) but it is labelled (2)

\begin{equation}
  e^{i\pi}+1 = 0
  (\#eq:euler)
\end{equation}


I would like the equations to be numbered (1.1) and (2.1) they are actually labelled (1) (2)


Solution

  • By default bookdown::pdf_docuemnt2 uses the LaTeX article class, which does not have any chapters. If you explicitly change this to use book or report class, the equations will be appropriately numbered:

    ---
    number_sections: true
    fig_caption: yes
    title: "Test equation nos"
    documentclass: book
    output: 
      bookdown::pdf_document2: default
    ---
    
    # Chapter 1
    
    I would like this equation to be numbered (1.1) but it is just labelled (1)
    
    \begin{equation}
      e = mc^2
      (\#eq:emc)
    \end{equation}
    
    # Chapter 2
    
    I would like this equation to be numbered (2.1) but it is labelled (2)
    
    \begin{equation}
      e^{i\pi}+1 = 0
      (\#eq:euler)
    \end{equation}
    

    However, this will result in a much longer document, since chapters start on a new page etc. If you are interested in a article like document with equations numbered per section, you can adept this answer:

    ---
    number_sections: true
    fig_caption: yes
    title: "Test equation nos"
    output: 
      bookdown::pdf_document2: default
    header-includes:
        - \usepackage{amsmath}
        - \numberwithin{equation}{section}
    ---
    
    # Chapter 1
    
    I would like this equation to be numbered (1.1) but it is just labelled (1)
    
    \begin{equation}
      e = mc^2
      (\#eq:emc)
    \end{equation}
    
    # Chapter 2
    
    I would like this equation to be numbered (2.1) but it is labelled (2)
    
    \begin{equation}
      e^{i\pi}+1 = 0
      (\#eq:euler)
    \end{equation}
    

    You can put these commands also in a preamble .tex file if you are using one.