【发布时间】:2018-07-29 20:26:52
【问题描述】:
我正在创建一个文档,在该文档中多次重复相同的格式。所以我想使用 R 中的for 循环来自动化这个过程。这是一个简单的例子。
假设,我有一个 R 代码,它计算 ggplot2::diamonds 数据集中所有 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
}
我该怎么做?
即,如何在我的主 Rmd 代码中插入一个 R 代码,告诉它插入其他 Rmd 代码(在 for 循环中) - 为五种类型的钻石切割自动生成五个部分?
附言。
我找到了这些相关的帖子:
Reusing chunks in Knitr 和
Use loop to generate section of text in rmarkdown
但还不能为上述示例重新创建解决方案。
【问题讨论】:
标签: r knitr r-markdown