Search code examples
latexr-markdown

How to get a static hardcoded table with number, caption and reference in Rmarkdown?


I am trying to include a table in an Rmarkdown document, which is going to be rendered both in PDF and in HTML. I would like the table to float in the PDF version, and have a running number and a caption, and be linkable using \@ref.

Everything I have found in the interwebs is about how to produce a dynamic table based on some structure, using knitr and variants. I don't want that. I want a static, hardcoded table, and I have not been able to get this to work.

As an example, I have the following in my file tabletest.Rmd:

---
output: pdf_document
---

Lorem ipsum

|             | Covered   | Not covered   |
| :---------- | :-------: | ------------: |
| Observed    | $k$       | $n-k$         |
| Expected    | $qn$      | $(1-q)n$      |

See Table X.

This is roughly the output I would like in PDF:

desired output

I created the desired output by LaTeXing a file with these contents:

\documentclass{article}
\begin{document}
Lorem ipsum

\begin{table}
  \begin{tabular}{|c|c|c|}
    & Covered & Not covered \\ \hline
    Observed & $k$ & $n-k$ \\
    Expected & $qn$ & $(1-q)n$
  \end{tabular}
  \caption{A table}\label{ref: table}
\end{table}
See Table \ref{ref: table}.
\end{document}

Solution

  • You have to use bookdown::pdf_document2, rather than (rmarkdown::)pdf_document, to use cross-references within a document, as explained in 4.7 Cross-referencing within documents of R Markdown Cookbook. You can make a cross-reference to a table by inserting (\#tab:label) to the table caption and by refering the table using \@ref(tab:label). See also the second paragraph from the last in 2.5 Tables of bookdown: Authoring Books and Technical Documents with R Markdown.

    ---
    output:
      bookdown::pdf_document2: default
    ---
    
    Lorem ipsum
    
    |             | Covered   | Not covered   |
    | :---------- | :-------: | ------------: |
    | Observed    | $k$       | $n-k$         |
    | Expected    | $qn$      | $(1-q)n$      |
    
    Table: (\#tab:ref2tab-first) The caption for the first table
    
    
    See Table \@ref(tab:ref2tab-first)
    and compare it with Table \@ref(tab:ref2tab-second).
    
    |             | purchased   | Not purchased   |
    | :---------- | :---------: | :-------------: |
    | food        | sausage     | bread           |
    | book        | bookdown    | cookbook        |
    
    Table: (\#tab:ref2tab-second) The caption for the second table