无法引用名为 R-chunk 的内容

Named R-chunk can't be referd to

下面的 MWE 应该通过 \@ref(fig:chunk-label) 引用它来正确显示图形的编号,但函数找不到引用。是否有任何选项必须添加到块 header 才能获得正确的引用?

MWE:

    ---
title: "Untitled"
author: "dsf"
date: "18 1 2022"
output:
  bookdown::pdf_document2:
    keep_tex: yes
    fig_caption: true
    number_sections: true
toc: true
lot: true
lof: true
graphics: true
---

```{r decision-tree, fig.cap="Decision Tree Example for the strava irmi dataset", echo= FALSE, message = FALSE}
library(rpart)
library(rattle)
library(tidyverse)
attach(mtcars)
train <- mtcars
train <- train %>% 
  mutate(across( .cols = everything(),  ~scale(.x)))
# Create a decision tree model
tree <- rpart(mpg~., data=train, cp=.05)

# Visualize the decision tree with rpart.plot
fancyRpartPlot(tree,yesno=2,split.col="black",nn.col="black", 
               caption="Decision Tree Example for the irmi dataset",palette="Set3",branch.col="black")
```
 Figure \@ref(fig:decision-tree) shows an example of an decision tree for the irmi dataset. 

编辑:感谢 stefan。我密切关注 并更新了 MWE。很遗憾,解决方案并没有解决问题![​​=14=]

这个问题很微妙。为了使参考有效,您必须在代码块和以下文本之后添加一个换行符:

---
title: "Untitled"
author: "dsf"
date: "18 1 2022"
output:
  bookdown::pdf_document2:
    keep_tex: yes
    fig_caption: true
    number_sections: true
toc: true
lot: true
lof: true
graphics: true
---

```{r decision-tree, fig.cap="Decision Tree Example for the strava irmi dataset", echo= FALSE, message = FALSE}
library(rpart)
library(rattle)
library(tidyverse)
attach(mtcars)
train <- mtcars
train <- train %>% 
  mutate(across( .cols = everything(),  ~scale(.x)))
# Create a decision tree model
tree <- rpart(mpg~., data=train, cp=.05)

# Visualize the decision tree with rpart.plot
fancyRpartPlot(tree,yesno=2,split.col="black",nn.col="black", 
               caption="Decision Tree Example for the irmi dataset",palette="Set3",branch.col="black")
```

Figure \@ref(fig:decision-tree) shows an example of an decision tree for the irmi dataset.