IVIM
IVIM

Reputation: 2367

Automating the generation of preformated text in Rmarkdown using R

I'm creating a document in which I repeat the same formatting multiple times. So I want to automate the process using the for loop in R. Here's a simple example.

Assume, I have an R code that computes some information for all cut values in ggplot2::diamonds dataset, which I want then to print in my document in five separate sections (one section per cut):

library(knitr); library(data.table) 

dt <- data.table(ggplot2::diamonds)
for (cutX in unique(dt$cut)) {
  dtCutX <- dt[cut==cutX, lapply(.SD,mean), .SDcols=5:7]

  #### START of the Rmd part that needs to be printed

  # Section: The Properties of Cut `cutX`  
  <!-- NB: This is the Section title in Rmd format, not the comment in R format ! -->

  This Section describes  the properties of cut `r cutX`. Table below shows its mean values:

  `r knitr::kable(dtCutX)`

  The largest carat value for cut `r cutX` is `r dt[cut=='Ideal', max(carat)]`

  #### END of the Rmd part that needs to be printed

}

How do I do that?
I.e., How do I insert inside my main Rmd code an R code that tells it to insert other Rmd codes (in a for loop) - to produce automatically five Sections for five types of diamond cuts?

PS.
I found these related posts:
Reusing chunks in Knitr and Use loop to generate section of text in rmarkdown but was not able yet to recreate the solution for the above example.

Upvotes: 3

Views: 1045

Answers (1)

RLesur
RLesur

Reputation: 5910

For this kind of task, you can use glue package to evaluate R expressions inside character strings.

Here's an Rmd file that answer your question:

---
title: "Untitled"
output: html_document
---

```{r echo=FALSE, results='asis'}
library(data.table) 

dt <- data.table(ggplot2::diamonds)
for (cutX in unique(dt$cut)) {
  dtCutX <- dt[cut==cutX, lapply(.SD,mean), .SDcols=5:7]
  cat("\n\n# Section: The Properties of Cut `cutX`\n")  
  cat(glue::glue("This Section describes the properties of cut {cutX}. Table below shows its mean values:\n"))
  print(knitr::kable(dtCutX))
  cat(glue::glue("\n\nThe largest carat value for cut {cutX} is {dt[cut=='Ideal', max(carat)]}\n"))
}
```

Upvotes: 2

Related Questions