Extending the example (R markdown: Use for loop to generate text and display figure/table ), I want to not only use a for loop to display figures but I also want to reference them using bookdown syntax: \@ref(fig:)
I modified the example by adding a reference and only printing the figures:
---
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")
}
```
I then rendered the Rmd file using bookdown::html_document2()
rmarkdown::render(
input = "figures_for_loop.Rmd",
output_format = bookdown::html_document2(),
clean = TRUE,
quiet = FALSE
)
The r document contains
# 0.1 Example
A summary of mtcars (Figures ??)
with this warning printed to the console.
Warning message:
The label(s) fig:lab-plot not found
How would I generate the reference (Figures 1-5)