PDF table captions don't use section/subsection

Hi all! I'm wondering if anyone has suggestions on how to have the PDF table captions make use of the section/subsection, rather than just being straight up numbered.

If a table is in the second section of an R Markdown document and the output is PDF, the table is "Table 1":

---
title: "Caption test"
output: bookdown::pdf_document2
---

# Section 1

No tables here!

# Section 2 

```{r, echo=FALSE}
library(knitr)

kable(
  head(mtcars[, 1:8], 10), booktabs = TRUE,
  caption = 'A table of the first 10 rows of the mtcars data.'
)
```

The output looks like this:

If I change the output to be HTML, it's Table 2.1!

---
title: "Caption test"
output: bookdown::html_document2
---

# Section 1

No tables here!

# Section 2 

```{r, echo=FALSE}
library(knitr)

kable(
  head(mtcars[, 1:8], 10), booktabs = TRUE,
  caption = 'A table of the first 10 rows of the mtcars data.'
)
```

I'd really like the caption to be "Table 2.1" in the PDF case -- is this something that I can change in e.g. a latex template?

Thanks!

Luke Turcotte pointed me in the direction of this SO question which helped me solve it!

---
title: "Caption test"
output: bookdown::pdf_document2
header-includes:
  - \counterwithin{table}{section}
---

# Section 1

No tables here!

# Section 2 

```{r, echo=FALSE}
library(knitr)

kable(
  head(mtcars[, 1:8], 10), booktabs = TRUE,
  caption = 'A table of the first 10 rows of the mtcars data.'
)
```

produces this:

and I can change section to subsection to make it use those, if they're present, too!

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.