【问题标题】:R Knitr PDF: Is there a posssibility to automatically save PDF reports (generated from .Rmd) through a loop?R Knitr PDF:是否可以通过循环自动保存 PDF 报告(从 .Rmd 生成)?
【发布时间】:2015-08-05 23:17:29
【问题描述】:

我想创建一个循环,它允许我自动保存从 .Rmd 文件生成的 PDF 报告。例如,如果变量“ID”有 10 行,我希望 R 自动将 10 个报告保存到特定目录中。这些报告应根据所选的 ID 有所不同。

之前的一篇文章 (Using loops with knitr to produce multiple pdf reports... need a little help to get me over the hump) 讨论了如何创建从 .Rnw 文件生成的多个 pdf 报告。我尝试按如下方式应用该方法:

#Data

```{r, include=FALSE}
set.seed(500)
Score <- rnorm(40, 100, 15)
Criteria1<-rnorm(40, 10, 5)
Criteria2<-rnorm(40, 20, 5)
ID <- sample(1:1000,8,replace=T)
df <- data.frame(ID,Score,Criteria1,Criteria2)

#instead of manually choosing the ID:

subgroup<- subset(df, ID==1) 

# I would like to subset the Data through a loop. My approach was like like this:

for (id in unique(df$ID)){
subgroup<- df[df$ID == id,]}

```

```{r, echo=FALSE}
#Report Analysis

summary(subgroup)
```
#Here will be some text about the summary.



# At the end the goal is to produce automatic pdf reports with the ID name as a filename:

library("rmarkdown")
render("Automated_Report.rmd",output_file = paste('report.', id, '.pdf', sep=''))

【问题讨论】:

  • 您需要一个循环,而不是两个。设置代码的方式是循环遍历所有子组,然后在完成后创建一堆 PDF。您需要将这些组合起来:选择一个子组并在同一循环中基于它创建一个报告。如果您需要更多帮助,则必须比“似乎不起作用”更具体,并且可能创建一个可重复的示例。
  • 您也可以查看knit_expandbrew 包。
  • 我也试过只用一个循环来做子集。但这也没有用。我提供了一个简单的可重现示例,它仅将每个 ID 的摘要粘贴到报告中,并将 knit2pdf() 函数与 rmarkdown 包中的 render() 函数进行了交换。@Gregor

标签: r pdf dynamic report knitr


【解决方案1】:

调整你的例子:

您需要一个.rmd“模板”文件。可能是这样的,保存为template.rmd

This is a subgroup report.

```{r, echo=FALSE}
#Report Analysis
summary(subgroup)
```

然后,您需要一个 R 脚本来加载您想要的数据,循环遍历数据子集,并针对每个子集

  1. 定义模板内使用的subgroup对象
  2. 将模板渲染到所需的输出

所以,在这个单独的脚本中

# load data 
set.seed(500)
Score <- rnorm(40, 100, 15)
Criteria1<-rnorm(40, 10, 5)
Criteria2<-rnorm(40, 20, 5)
ID <- sample(1:1000,8,replace=T)
df <- data.frame(ID,Score,Criteria1,Criteria2)

library("rmarkdown")

# in a single for loop
#  1. define subgroup
#  2. render output
for (id in unique(df$ID)){
    subgroup <- df[df$ID == id,]
    render("template.rmd",output_file = paste0('report.', id, '.html'))    
}

这在我的工作目录中生成了 8 个 html 文件,每个文件都有不同数据子集的摘要。

请注意,如果您尝试单击 RStudio 中的“编织”按钮,这将不起作用,因为它会在单独的 R 会话中运行 R 代码。但是,当您从控制台显式使用render(或knit2pdf)运行时,rmd 文件中的 R 代码仍然可以访问全局环境。

除了依赖全局变量,另一种选择是使用parametrized reports,在 YAML 标头中定义参数,并将参数值作为参数传递给rmarkdown::render

【讨论】:

  • 感谢@Gregor这工作!我猜你选择了 .html 因为 .pdf 基于摘要的 pandoc 输出创建了一个错误。因为这无论如何只是一个简单的例子,最终并没有什么不同。
  • 是的,我认为这将有助于制定一般原则,并且内容的细节很容易遵循。
猜你喜欢
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多