Automating the generation of preformated text in Rmarkdown using R

扶醉桌前 提交于 2019-12-20 01:58:17

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/48868942/automating-the-generation-of-preformated-text-in-rmarkdown-using-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!