Dylan Russell
Dylan Russell

Reputation: 1098

R Markdown - cross reference an HTML table without `kable`

All the questions regarding table cross-referencing in a Rmarkdown document require using kable to cross-reference. How can I cross-reference an HTML table not produced from kable? For example, using the table1 package:

---
title: Test Table Cross-Reference
output: bookdown::html_document2
---

This should be a cross reference to table \@ref(tab:table).

```{r table, echo = FALSE}
table1::table1(~depth + table + price | cut, data = ggplot2::diamonds)
```

Upvotes: 1

Views: 490

Answers (1)

Martin C. Arnold
Martin C. Arnold

Reputation: 9658

This is not as easy as with kable, where knitr automatically creates the link and reference and inserts both into the final HTML document. However, if you can live without automatic numbering it is easy to create links yourself.

You can create a caption using HTML, anchor it via the argument id and then link to that anchor like this (this is similar to what knitr does automatically):

This should be a cross reference to table [1](#tab:table)

```{r table2, echo = FALSE}
table1::table1(~depth + table + price | cut, data = ggplot2::diamonds)
```

<center><p id='tab:table'> Table 1: Your Caption</p></center>

Note that table1::table1() also has an option caption to which you may pass a a character string, so something like this works too:

```{r table2, echo = FALSE}
table1::table1(~depth + table + price | cut, data = ggplot2::diamonds,
               caption = "<p id='tab:table'> Table 1: Your Caption</p>")
```

enter image description here

Upvotes: 3

Related Questions