Home > Mobile >  RMarkdown: cannot reference the label of a `knitr::kable` table
RMarkdown: cannot reference the label of a `knitr::kable` table

Time:12-15

I am having trouble referencing the label of a knit::kable table in a r markdown file.

Here is a minimal reproduce of this error. This is my r markdown file:

---
output:
  pdf_document:
    number_sections: yes
tables: true
---

Trying to reference Table \ref{some_label}.

```{r}
df <- data.frame(
    x1 = c(1,2,3),
    x2 = c(4,5,6)
)

df |> knitr::kable(
  digits = 3,
  label = "some_label"
)
``` 

My generated pdf is this: enter image description here

As you can see, I got Table ??

Anyone know what's causing this? How can I fix this?

CodePudding user response:

Latex needs to know with which number it can reference an object, therefore you can only reference tables which have a caption.

---
output:
  pdf_document:
    number_sections: yes
    keep_tex: true
tables: true
---

Trying to reference Table \ref{somelabel}.

```{r}
df <- data.frame(
    x1 = c(1,2,3),
    x2 = c(4,5,6)
)

df |> knitr::kable(
  digits = 3,
  caption = "This is the table caption\\label{somelabel}",
)
``` 

enter image description here

  • Related