1

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)

phargart
  • 655
  • 3
  • 14

1 Answers1

0

Here is an option using knit_expand and purrr::map_chr():

---
title: "R Notebook"
output: bookdown::html_document2
---

# Example

A summary of mtcars can be found in (**Figures \@ref(fig:plot-1), \@ref(fig:plot-2) \@ref(fig:plot-3),\@ref(fig:plot-4),\@ref(fig:plot-5) **)


```{r results='asis', echo=FALSE}
 df <- mtcars[sample(5),]
structure_text <- purrr::map_chr(1:5, \(x) {
  knitr::knit_expand(text = c(
    "",
    "```{r 'plot-{{x}}', echo = FALSE, fig.cap = '\\\\label{fig:plot-{{x}}} Mtcars plot {{x}}.'}",
    "  g1 <- ggplot2::ggplot(df, ggplot2::aes(x = mpg, y = disp, fill = gear)) +",
    "ggplot2::geom_point() +",
    "ggplot2::labs(title = paste0('Figure ', {{x}}))",
    "print(g1)",
    "```",
    ""
    ))
})
res <- knitr::knit_child(text = structure_text, quiet = TRUE)
cat(res, sep = '\n')
```

Output preview:

enter image description here

Julian
  • 6,586
  • 2
  • 9
  • 33