0
votes

In my Rmarkdown report, most of sections have the same text, inline code and R code chunk. Is it possible to parameterize them? For example the below image, is it possible to use something like for loop to produce them instead of repeating similar code 3 times?

enter image description here

2
Perhaps using a 'child' document in this situation might be helpful. For more info see bookdown.org/yihui/rmarkdown-cookbook/child-document.htmlmarkdly

2 Answers

1
votes

In main RMD file,

library(tidyverse)

dat <- tibble(
  id = 1:3,
  fruit = c("apple", "orange", "banana"),
  sold = c(10, 20, 30)
)
res <- lapply(dat$id, function(x) {
  knitr::knit_child(
    'template.Rmd', envir = environment(), quiet = TRUE
  )
})
cat(unlist(res), sep = '\n')

In template.RMD,

current_dat <- filter(dat, id == x)
# Section: `r  current_dat$fruit`
current_dat %>% 
  ggplot(aes(x = fruit, y = sold)) + geom_col()
0
votes

IMHO, the simplest wat to achieve this is to use results = 'asis' and cat() below is a minimal RMarkdown file.

---
title: "Minimal example"
---

```{R results = "asis"}
for (i in 1:3) {
 x <- runif(10)
 cat("# section", floor(i), "\n")
 plot(x)
 # line break
 cat("\n\n")
}
```