knitr/rmarkdown/Latex: How to cross-reference figures and tables?

You can use the output format bookdown::pdf_document2 instead of pdf_document, and the syntax for referencing a figure is \@ref(fig:chunk-label); see the documentation for details: https://bookdown.org/yihui/bookdown/figures.html


Following I can't generate \label{fig:mwe-plot} with knitr, adding \label{...} to the caption arguments will produce labels in the underlying tex file, i.e.

```{r fig1, echo=FALSE, fig.cap="\\label{fig:fig1}This is a caption"}
plot(mtcars$wt, mtcars$mpg)
```

and

```{r tab2, echo=FALSE}
library(knitr)
kable(mtcars[1:3,1:4], caption="\\label{tab:tab2}A `kable` table")
```

You can try the captioner package. You can find examples in this link.

In my case, I include a code chunk with:

table_captions <- captioner::captioner(prefix="Tab.")
figure_captions <- captioner::captioner(prefix="Fig.")

t.ref <- function(label){
  stringr::str_extract(table_captions(label), "[^:]*")
}

f.ref <- function(label){
  stringr::str_extract(figure_captions(label), "[^:]*")
}

I include captions in tables and figures when defining code chunks, like this:

```{r chunk_creating_one_figure, echo=FALSE, fig.cap=figure_captions("one_figure", "figure label")}
plot(1)
```

or

```{r chunk_creating_one_table, echo=FALSE, fig.cap=table_captions("one_table", "table label")}
knitr::kable(data.frame(col="something"), format="markdown")
```

References are included as inline_text all across my Rmarkdown with:

As shown in figure `r f.ref("one_figure")`
Data is shown on table `r t.ref("one_table")`