3

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.

IVIM
  • 2,167
  • 1
  • 15
  • 41

1 Answers1

2

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"))
}
```
RLesur
  • 5,810
  • 1
  • 18
  • 53
  • A wonderful package! I'm trying your code now and find that the following line does not seem to work : `cat("\n\n# Section: The Properties of Cut `cutX`\n") `. You probably meant `cat(glue::glue("\n\n# Section: The Properties of Cut {cutX} \n"))` ? But the latter does glue correctly either (it glues next line to become a continuation of Section title. Any idea to fix it? – IVIM Feb 19 '18 at 22:42
  • It works now ! - it should end with two `\n`'s . `cat(glue::glue("\n\n# Section: The Properties of Cut {cutX} \n \n "))`. Thanks! – IVIM Feb 19 '18 at 22:46
  • I scrupulously followed your question: you wrote "`cutX`" and not "`r cutX`". That's why I answered "`cutX`" and not "{cutX}" – RLesur Feb 19 '18 at 22:47