扩展示例(R markdown: Use for loop to generate text and display figure/table ),我不仅想使用for循环来显示图形,而且我还想使用bookdown语法引用它们:
\@ref(fig:)
我通过添加参考并仅打印数字来修改示例:
---
title: "R Notebook"
output: bookdown::html_document2()
---
## Example
A summary of mtcars (**Figures \@ref(fig:lab-plot)**)
```{r lab-plot, results='asis'}
require(ggplot2)
for(i in 1:5){
# cat("### Section ", i, "\n")
df <- mtcars[sample(5),]
tb <- knitr::kable(df, caption = paste0("Table",i))
g1 <- ggplot2::ggplot(df, aes(x = mpg, y = disp, fill = gear)) +
ggplot2::geom_point() +
ggplot2::labs(title = paste0("Figure ", i))
cat("\n")
print(g1)
# print(tb)
cat("\n")
}
```
然后我使用
bookdown::html_document2()
渲染 Rmd 文件
rmarkdown::render(
input = "figures_for_loop.Rmd",
output_format = bookdown::html_document2(),
clean = TRUE,
quiet = FALSE
)
r文件包含
# 0.1 Example
A summary of mtcars (Figures ??)
此警告打印到控制台。
Warning message:
The label(s) fig:lab-plot not found
我将如何生成参考
(Figures 1-5)