问题
I'm trying to create automated PDF RMarkdown reports for fitness testing data based on the training hub city.
I believe I'm very close by following the outline here: R Knitr PDF: Is there a posssibility to automatically save PDF reports (generated from .Rmd) through a loop?
However, this is creating reports with the same data for only 1 hub despite both being named differently (report.MTL.pdf and report.TOR.pdf). How can I get the subgroup to loop properly to show data from the different hubs?
Sample data:
Date Athlete Test Average Hub
1 2019-06-03 Gabel Broad_Jump 175.000000 TOR
2 2019-06-10 Gabel Broad_Jump 187.000000 TOR
3 2019-06-10 Clark Broad_Jump 200.666667 MTL
4 2019-06-10 Pozzebon 10m_Sprint 1.831333 MTL
5 2019-06-10 Clark 10m_Sprint 2.026667 MTL
6 2019-06-17 Gabel Broad_Jump 191.500000 TOR
7 2019-06-17 Clark Broad_Jump 200.666667 MTL
8 2019-06-17 Pozzebon 10m_Sprint 1.803667 MTL
9 2019-06-17 Clark 10m_Sprint 2.090000 MTL
10 2019-06-24 Gabel Broad_Jump 192.000000 TOR
R Script for Rendering RMarkdown
NWT <- read.csv("NWT.csv")
for (hub in unique(NWT$Hub)){
subgroup <- subset(NWT, Hub == hub)
render("Hub_Test.rmd",output_file = paste0('report.', hub, '.pdf'))
}
RMarkdown File (Hub_Test.rmd):
NWT <- read.csv("NWT.csv")
for (hub in unique(NWT$Hub)){
subgroup <- subset(NWT, Hub == hub)
}
summary(subgroup)
This set up creates 2 PDFs in my working directory with ONLY MTL data. I must be missing something.
回答1:
hub
is passed to Hub_Test.rmd
, so you don't need to write the loop in the rmd file. The other issue is that I believe pandoc has some issues writing to pdf with summary
, so I'm using html output here, but the general idea is the same.
Hub_Test.rmd
```{r, echo=FALSE}
NWT <- structure(list(Athlete = structure(2:1, .Label = c("Clark", "Gabel"
), class = "factor"), Test = structure(2:1, .Label = c("10m_Sprint",
"Broad_Jump"), class = "factor"), Hub = structure(2:1, .Label = c("MTL",
"TOR"), class = "factor")), class = "data.frame", row.names = c(NA,
-2L))
subgroup <- subset(NWT, Hub == hub)
summary(subgroup)
```
generation script
library(rmarkdown)
NWT <- structure(list(Athlete = structure(2:1, .Label = c("Clark", "Gabel"
), class = "factor"), Test = structure(2:1, .Label = c("10m_Sprint",
"Broad_Jump"), class = "factor"), Hub = structure(2:1, .Label = c("MTL",
"TOR"), class = "factor")), class = "data.frame", row.names = c(NA,
-2L))
for (hub in unique(NWT$Hub)){
subgroup <- subset(NWT, Hub == hub)
render("Hub_Test.rmd",output_file = paste0('report.', hub, '.html'))
}
来源:https://stackoverflow.com/questions/59415974/multiple-automatic-reports-with-subgroup-loop-in-r