在for循环中使用不同的区块选项和降价标题创建R降价区块

wztqucjr  于 2023-02-20  发布在  其他
关注(0)|答案(2)|浏览(128)

我想在R中的for循环内为data.frame s的list自动生成R markdown块和标题,长度根据输入而变化。这些是绘图生成的输入。然后使用knitr包将此R markdown文档编织到html_document中。
我已经尝试了几个类似的SO问题的解决方案,这些问题可以让我接近,但不是我实际需要的:

下面是我的一次失败尝试的示例(注意:下面的第二个代码块还包含指示所需的块选项的注解):

# Chunk data demo
data_list <- list(a=data.frame(), b=data.frame(), c=data.frame())
plot_1 <- list()
plot_2 <- list()

for (i in 1:length(data_list)) {
  data_list[[i]] <- data.frame(x = 1:5, y = 1:5)
  plot_1[[i]] <- ggplot(data_list[[i]], aes(x, y)) + geom_point()
  plot_2[[i]] <- ggplot(data_list[[i]], aes(x, y)) + geom_point()
}
#```{r, results='asis'} (Start of R markdown chunk)

# Chunk generation (only 2 chunks are written for brevity)   
for (i in 1:length(data_list)) {
  # Section heading
  cat("\n\n")
  cat("##", names(data_list)[i])

  # Chunk 1 ----
  cat("\n\n")
  cat("### Sub-section 1")
  cat("\n\n")
  cat("**Title 1**")
  cat("\n\n")
  cat('```{r, fig.width=10, fig.height=10}')
  cat("\n\n")
  print(plot_1[[i]])
  cat("\n\n")
  cat('```')
    
  # Chunk 2 ----
  cat("\n\n")
  cat("### Sub-section 2")
  cat("\n\n")
  cat("**Title 2**")
  cat("\n\n")
  cat('```{r, fig.width=10, fig.height=3}') # NOTE: Change in option
  cat("\n\n")
  print(plot_2[[i]])
  cat("\n\n")
  cat('```')
  cat("\n\n")
}
#``` (End of R markdown chunk)
  • 编辑:删除ggsave()调用,因为没有必要说明编织文件中明显的问题。*
6pp0gazn

6pp0gazn1#

我知道你想做什么,我认为你采取的方法不会起作用。(但我猜你已经知道了!)以下是原因:
当你运行asis块时,你产生的是Markdown,而不是R Markdown。fig.widthfig.height选项需要由knitr在处理R Markdown时处理,但这只发生一次。处理Markdown的下一个阶段由Pandoc完成,它不知道fig.widthfig.height的任何信息。
所以你需要做的就是生成一个“子文档”,然后让knitr把它包含在你的主文档中,这些内容如下所述:https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html。基本上,它们只是R Markdown的一部分,需要包含在主文档中。下面是对文档的修改:

---
title: "Untitled"
author: "Duncan Murdoch"
date: "2023-02-12"
output: 
  html_document:
    keep_md: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

R Markdown

library(ggplot2)
# Create the plots
data_list <- list(a=data.frame(), b=data.frame(), c=data.frame())
plot_1 <- list()
plot_2 <- list()

for (i in 1:length(data_list)) {
  data_list[[i]] <- data.frame(x = 1:5, y = 1:5)
  plot_1[[i]] <- ggplot(data_list[[i]], aes(x, y)) + geom_point()
  plot_2[[i]] <- ggplot(data_list[[i]], aes(x, y)) + geom_point()
}
# Create a child document
child <- "child.Rmd"
cat("\n", file = child)

# Save typing file = child, append = TRUE every time
# by making a new function to call cat

cat2 <- function(...) cat(..., file = child, append = TRUE)

for (i in 1:length(data_list)) {
  # Section heading
  cat2("\n\n")
  cat2("##", names(data_list)[i])

  # Chunk 1 ----
  cat2("\n\n")
  cat2("### Sub-section 1")
  cat2("\n\n")
  cat2("**Title 1**")
  cat2("\n\n")
  cat2('```{r fig.width=10, fig.height=10}')
  cat2("\n\n")
  cat2("i = ", i, "\n")
  cat2("print(plot_1[[i]])")
  cat2("\n\n")
  cat2('```')
    
  # Chunk 2 ----
  cat2("\n\n")
  cat2("### Sub-section 2")
  cat2("\n\n")
  cat2("**Title 2**")
  cat2("\n\n")
  cat2("```{r fig.width=10, fig.height=3}")
  cat2("\n\n")
  cat2("print(plot_2[[i]])")
  cat2("\n\n")
  cat2('```')
  cat2("\n\n")
}
wljmcqd8

wljmcqd82#

也可以使用knitr::knit_expand()并将其传递给knitr::knit_child()函数。

    • 编辑**:
---
output: html_document
---

```{r, echo=FALSE, results='asis'}
library(purrr)
library(ggplot2)
data_list <- list(a=data.frame(x = 1:5, y = 1:5), b=data.frame(x = 1:5, y = 1:10),  c=data.frame(x = 1:5, y = 1:15))

data_plots_1 <- map(data_list, ~ggplot(.x, aes(x, y)) + geom_point())
data_plots_2 <- map(data_list, ~ggplot(.x, aes(x, y)) + geom_point(color = "red"))

fig_width <- c(7,5,5)
fig_height <- c(5,3,3)

data_names <- data_list %>% names()
structure_text <- purrr::pmap_chr(list(data_names, fig_width, fig_height), \(data_names,  fig_width, fig_height) {
  knitr::knit_expand(text = c(
    "## Title Plot 1 dataset {{data_names}}", 
    "",
    "",
    "```{r, fig.width= {{ fig_width }},  fig.height= {{ fig_height }}, echo =FALSE }",
    "data_plots_1${{data_names}} ",
    "```",
    "",
    "## Title Plot 2 dataset {{data_names}}", 
    "",
    "",
    "```{r, fig.width= {{ fig_width }},  fig.height= {{ fig_height }}, echo =FALSE }",
    "data_plots_2${{data_names}} ",
    "```",
    ""
    ))
})
res <- knitr::knit_child(text = structure_text, quiet = TRUE)
cat(res, sep = '\n')

    • 旧**
---
output: html_document
---

```{r, echo=FALSE, results='asis'}
library(purrr)
library(ggplot2)
data_list <- list(a=data.frame(x = 1:5, y = 1:5), b=data.frame(x = 1:5, y = 1:10))
data_names <- data_list %>% names()
fig_width <- c(7,5)
fig_height <- c(5,3)
structure_text <- purrr::pmap_chr(list(data_names, fig_width, fig_height), \(data_names, fig_width, fig_height) {
  knitr::knit_expand(text = c(
    "## {{ data_names }}", 
    "",
    "",
    "```{r, fig.width= {{ fig_width }},  fig.height= {{ fig_height }}, echo =FALSE }",
    "data_list${{data_names}}  |>",
    "  ggplot(aes(x = x, y = y)) +",
    "  geom_point()",
    "```",
    ""))
})
res <- knitr::knit_child(text = structure_text, quiet = TRUE)
cat(res, sep = '\n')

相关问题