How to add a caption *above* a table with `knitr::kable`?

Viewed 544

When I render a simple Rmarkdown document as github_document, the table caption appears below the table rather than above. It also lacks the "Table: " prefix. Is there any way to change this behavior? Xie Yihui has made clear that kable's default caption position should be above the table and when I run the same command outside of the Rmarkdown file, the caption does indeed appear on top.

The command I am referring to is

knitr::kable(mtcars, caption = "mtcars")

and my Rmarkdown document looks like this:

---
title: "Test"
output: github_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
knitr::kable(mtcars, caption = "mtcars")
```

Specifying format = "pipe" or format = "simple" does not seem to help.

1 Answers

When converting to a markdown output format knitr::kable() will default to format = "pipe". This is for pandoc's pipe tables. format = "simple" is for Pandoc's simple table.

Those two syntax are Pandoc's markdown syntax. Pandoc's supports caption to be provided (https://pandoc.org/MANUAL.html#extension-table_captions).

knitr will write that for you: the table and caption in expected format.

However, output is defined to Github Flavored Markdown, so Pandoc's gfm. This flavor of Markdown does not support caption. Hence Pandoc will convert the pipe table in another Markdown table and suppressing the caption syntax to place the text below the table. This is Pandoc doing.

Take this .md file

Table: Demonstration of pipe table syntax.

| Right | Left | Default | Center |
|------:|:-----|---------|:------:|
|   12  |  12  |    12   |    12  |
|  123  |  123 |   123   |   123  |
|    1  |    1 |     1   |     1  |

doing a pandoc conversion will lead to

❯ pandoc -t gfm test.md
| Right | Left | Default | Center |
|------:|:-----|---------|:------:|
|    12 | 12   | 12      |   12   |
|   123 | 123  | 123     |  123   |
|     1 | 1    | 1       |   1    |

Demonstration of pipe table syntax.

Pandoc is placing the caption below when output is gfm


Question also asked in https://github.com/yihui/knitr/issues/2074

Related