使用R在Rmarkdown中自动生成预格式化的文本 [英] Automating the generation of preformated text in Rmarkdown using R

查看:145
本文介绍了使用R在Rmarkdown中自动生成预格式化的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个文档,在其中我重复相同的格式多次.因此,我想使用R中的for循环来自动化该过程.这是一个简单的示例.

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.

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

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

}

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

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.
我发现了以下相关帖子:
在Knitr中重复使用块使用循环在rmarkdown中生成文本部分 但仍无法为上述示例重新创建解决方案.

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.

推荐答案

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

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

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

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

这篇关于使用R在Rmarkdown中自动生成预格式化的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆