ChenX
ChenX

Reputation: 121

How to parameterize the inline code, text, together with R code chunk in Rmarkdown

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

Upvotes: 1

Views: 586

Answers (2)

ChenX
ChenX

Reputation: 121

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()

Upvotes: 1

Kevin Cazelles
Kevin Cazelles

Reputation: 1255

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")
}
```

Upvotes: 0

Related Questions