chriad
chriad

Reputation: 1412

Referencing a table in R markdown with knitr

It's possible to reference a figure in knitr like that:

```{r myfig}
plot(1,1)
```

Figure \ref{fig:myfig} shows ...

The same is not possible for tables, e.g.

```{r my_table, results='markup', fig.cap='capture'}
tab <- read.table('my_table.txt', sep = '\t')
kable(tab, 
      format='pandoc', 
      digits = 3, 
      caption =
      "Description")
```

Table \ref{table:my_table} shows ...

doesn't work! Is it possible to make this work without digging into latex? If no, what would I have to do to make it work?

Upvotes: 2

Views: 3906

Answers (2)

Avlayort
Avlayort

Reputation: 33

Replace table with tab \@ref(tab:my_table)

Upvotes: 0

user2554330
user2554330

Reputation: 44977

With format='pandoc' you need to enter the \label command in the caption.

With format='latex' the reference is automatically created as tab:chunk_label. For example,

---
output: 
  pdf_document
tables: true
---

```{r results='markup'}
tab <- head(iris)
knitr::kable(tab, 
  format='pandoc', 
  digits = 3, 
  caption = "Pandoc table\\label{tab:pandoc_table}"
  )
```

```{r latex_table, results='markup'}
tab <- head(iris)
knitr::kable(tab, 
  format='latex', 
  digits = 3, 
  caption = "LaTeX table",
  booktabs = TRUE
  )
```

Table \ref{tab:pandoc_table} was done using Pandoc,
while Table \ref{tab:latex_table} used \LaTeX.

Upvotes: 3

Related Questions