【问题标题】:Automating the generation of preformated text in Rmarkdown using R使用 R 在 Markdown 中自动生成预格式化文本
【发布时间】: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 KnitrUse loop to generate section of text in rmarkdown 但还不能为上述示例重新创建解决方案。

【问题讨论】:

    标签: r knitr r-markdown


    【解决方案1】:

    对于此类任务,您可以使用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"))
    }
    ```
    

    【讨论】:

    • 一个很棒的包!我现在正在尝试您的代码,发现以下行似乎不起作用:cat("\n\n# Section: The Properties of Cut cutX\n") 。您可能是指 cat(glue::glue("\n\n# Section: The Properties of Cut {cutX} \n")) ?但是后者也可以正确粘合(它粘合下一行以成为部分标题的延续。有什么想法可以解决它吗?
    • 现在可以使用了! - 它应该以两个 \n 结尾。 cat(glue::glue("\n\n# Section: The Properties of Cut {cutX} \n \n "))。谢谢!
    • 我认真地听从了你的问题:你写的是“cutX”而不是“r cutX”。这就是为什么我回答“cutX”而不是“{cutX}”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2019-03-11
    • 2021-12-24
    • 2014-03-10
    • 1970-01-01
    相关资源
    最近更新 更多