【发布时间】: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_expand或brew包。 -
我也试过只用一个循环来做子集。但这也没有用。我提供了一个简单的可重现示例,它仅将每个 ID 的摘要粘贴到报告中,并将 knit2pdf() 函数与 rmarkdown 包中的 render() 函数进行了交换。@Gregor
标签: r pdf dynamic report knitr