R Knitr PDF:是否有可能通过循环自动保存 PDF 报告(从 .Rmd 生成)?

R Knitr PDF: Is there a posssibility to automatically save PDF reports (generated from .Rmd) through a loop?

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

之前的 post (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=''))

调整您的示例:

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

This is a subgroup report.

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

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

  1. 定义模板中使用的subgroupobject
  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 中的 "knit" 按钮,这将 不起作用 ,因为 运行 是单独 R 中的 R 代码session。但是,当您从控制台 运行 明确使用 render(或 knit2pdf)时,rmd 文件中的 R 代码仍然可以访问全局环境。

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