r-RMarkdown:一种从许多迷你RMarkdown文档中编写报告的方法



将tibble:视为输入

in_data <- tribble(
~ style, ~input1, ~input2, ~text_input
'style_1', 5, NA, 'first result',
'style_2', 4, 6, 'fun',
'style_1', 2, NA, 'other result')

我想做以下事情:

  • 有不同的模式,例如style_1style_2

style_1.Rmd

---
params:
input1: NA
text_input: ''
---
`r params$text_input` is of the value `r params$input1`

style_2.Rmd

---
params:
input1: NA
input2: NA
text_input: ''
---
```{r}
plot(params$input1, params$input2, main=params$text_input)
```
  • 以某种方式in_data %>% pmap(parse_and_knit)文档,其中每一行都编织有相应的样式和参数,并最终组成一个文档,可能需要额外的标题

存在heddlrhttps://github.com/mikemahoney218/heddlr其作用类似。但它似乎依赖于替换每个"1"的单个自变量;图案";(这是我的"风格"(。我可以把这个论点设为一个行号,然后用这个信息提取数据;以CCD_ 6样式将整行作为CCD_。

这可能吗?我可以单独knit每一个片段,但最终我需要将其编写成一个报告,最好不用做我自己的DOM魔术。

感谢@Jon Spring,下面的内容非常接近我想要的。

  • R脚本将数据帧作为rmarkdown::renderparams项传递
  • 在行之间循环的逻辑在报告模板中(而不是像我最初想要的那样,在触发报告生成的R脚本中(
  • 将行数据放入环境中,并使用envir传入。我也可以将列变量直接分配到envir中,这样就可以在没有data$的情况下直接访问它们,但我还不确定是否需要
  • 注:pwalk(..., ~cat(...))可能比cat(pmap_chr(...) %>% str_flatten())

在脚本generate_report.R中:

library(knitr)
library(tidyverse)
in_data <- tribble(
~ style, ~input1, ~input2, ~text_input,
'style1', 5, NA, 'first result',
'style2', 4, 6, 'fun',
'style1', 2, NA, 'other result')

rmarkdown::render("rmdreport.Rmd", params = list(data = in_data))

在报告模板report.Rmd

---
title: "report title"
output: html_document
params:
data: NA
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, results='asis')
```
# Report
This is the intro to the report. What follows is one block per row in `params$data`.
```{r}
in_data <- params$data
cat(
pmap_chr(in_data, function(...) {
data <- list(...)
envir = new.env()
envir$data <- data
knitr::knit_child(glue("{data$style}.rmd"), envir = envir, quiet = TRUE)
}) %>% str_flatten())
```

各个模板/样式:

样式1.Rmd

## Section on the topic `r data$text_input`
`r data$text_input` is of the value `r data$input1`

样式2.Rmd

## Section with a plot
```{r}
plot(data$input1, data$input2, main=data$text_input)
res <- data$input1 * data$input2
cat(glue("{data$input1} * {data$input2} = {res}"))
```

最新更新