How can I use a loop in RMarkdown to programmatically plot figures and text on individual pages in a document?

huangapple go评论115阅读模式
英文:

How can I use a loop in RMarkdown to programmatically plot figures and text on individual pages in a document?

问题

以下是翻译好的部分:

以下代码将在一个.Rmd文件中运行,循环遍历一个列表,并使用列表中位置为```i```的元素绘制一个图形。每个图形都绘制在新页面上,因此每个页面只包含一个图形。

*请注意,我在三个破折号前添加了撇号,以提高可读性。*

```markdown
---
output: word_document
---

'```{r setup, echo=FALSE, include=FALSE}
library(tidyverse)

make_df <- function(z){
  tibble(X = runif(n = 10, min = z, max = z * 2), Y = runif(n = 10, min = z, max = z * 2))
  }

'```

'```{r plots, results='asis', warning=FALSE, message=FALSE, echo=FALSE}

newslide <- function(options = "", heading = "", content) {
  code <- deparse(substitute(content))
  
  cat(sep = "\n", 
      knitr::knit_child(
        quiet = TRUE, 
        text = knitr::knit_expand(text = c("```{r {{options}} }", "{{code}}", "```"))))
}


for (i in 1:3) {
newslide(
  options = paste0("fig.width=6.5, fig.height=8.8, dpi = 600, warning=FALSE, message=FALSE, echo=FALSE"),
  content = plot(make_df(i))
)
}
'```

所有这些都运行良好!然而,我不仅仅想要图形,我也想要文字。我需要一个可以格式化的文本块(例如,我想要能够设置颜色、字体系列、大小等),以便在每个图形下方打印,并且不要看起来像##像这样(我通过在content变量中添加+ cat("xyz")来获得了不推荐的格式化)。

文本可以相同,它只是一个将应用于每个图形的标题,但我希望它打印出来并且可以编辑,即不是图形的一部分。

英文:

The code below will run in an .Rmd file to loop through a list and, using the element at position i in the list, plot a figure. Each figure is plotted on a new page, so that each page only contains one figure.

Note that I added apostrophes before the triple dash to improve readability here.

---
output: word_document
---

'```{r setup, echo=FALSE, include=FALSE}
library(tidyverse)

make_df <- function(z){
  tibble(X = runif(n = 10, min = z, max = z * 2), Y = runif(n = 10, min = z, max = z * 2))
  }

'```

'```{r plots, results='asis', warning=FALSE, message=FALSE, echo=FALSE}

newslide <- function(options = "", heading = "", content) {
  code <- deparse(substitute(content))
  
  cat(sep = "\n", 
      knitr::knit_child(
        quiet = TRUE, 
        text = knitr::knit_expand(text = c("```{r {{options}} }", "{{code}}", "```"))))
}


for (i in 1:3) {
newslide(
  options = paste0("fig.width=6.5, fig.height=8.8, dpi = 600, warning=FALSE, message=FALSE, echo=FALSE"),
  content = plot(make_df(i))
)
}
'```

All that works well! However, I don't just want figures, I want text, too. I need a block of nicely formattable text (eg I want to be able to set the color, font family, size, etc) to print below each figure and for it not to ## look like this (I was able to get the contraindicated formatting by adding + cat("xyz") in the content variable).

The text can be identical, it's just a caption that will apply to each figure, but I do want it to print and be editable, ie not part of the plot.

答案1

得分: 1

knit_child()函数的text参数中,你可以像这样添加代码,就好像你在R块内外都在写代码一样:

newslide <- function(options = "", heading = "", content) {
  code <- deparse(substitute(content))
  
  cat(sep = "\n", 
      knitr::knit_child(
        quiet = TRUE, 
        text = c("### Header 3",
          "```{r results = 'asis'}", # R块
          "#| echo: false", # R块的选项,如果不使用Quarto,可以删除这一行
          code, 
          "```",
          "",
          "文本将出现在图表下方,使用**Markdown**格式化"
        )
      )
  )
}
英文:

In the text argument of knit_child(), you can add code as if you were writing both inside and outside a R chunk, like this:

newslide &lt;- function(options = &quot;&quot;, heading = &quot;&quot;, content) {
  code &lt;- deparse(substitute(content))
  
  cat(sep = &quot;\n&quot;, 
      knitr::knit_child(
        quiet = TRUE, 
        #text = knitr::knit_expand(text = c(&quot;```{r {{options}} }&quot;, &quot;{{code}}&quot;, &quot;```&quot;))))
        text = c(&quot;### Header 3&quot;,
    &quot;```{r results = &#39;asis&#39;}&quot;, #the r chunk
    &quot;#| echo: false&quot;, #options for the chunk, you can delete this if not using Quarto
    code, 
    &quot;```&quot;,
    &quot;&quot;,
    &quot;Text that will be below your plot, formatted with **markdown** and all&quot;)
      )
  )
}

huangapple
  • 本文由 发表于 2023年8月11日 01:40:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定