使用R在Rmarkdown中自动生成预格式化文本

时间:2018-02-19 15:07:32

标签: r knitr r-markdown

我正在创建一个文档,其中我多次重复相同的格式。所以我想使用R中的for循环自动化这个过程。这是一个简单的例子。

假设我有一个R代码,用于计算cut数据集中所有ggplot2::diamonds值的一些信息,然后我希望在五个单独的部分(每个剪切一个部分)中打印在我的文档中:

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

}

我该怎么做?
即,如何在我的主Rmd代码中插入一个R代码,告诉它插入其他Rmd代码(在for循环中) - 自动生成五个类型的五种钻石切割?

PS。
我找到了这些相关的帖子:
Reusing chunks in KnitrUse loop to generate section of text in rmarkdown 但是还没有为上面的例子重新创建解决方案。

1 个答案:

答案 0 :(得分:2)

对于此类任务,您可以使用glue包来评估字符串中的R表达式。

这是一个回答您问题的Rmd文件:

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