vb66
vb66

Reputation: 373

Multiple Automatic Reports with Subgroup Loop in R

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.A.pdf and report.B.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    Athlete1 Broad_Jump 175.000000 A
2  2019-06-10    Athlete1 Broad_Jump 187.000000 A
3  2019-06-10    Athlete2 Broad_Jump 200.666667 B
4  2019-06-10 Athlete3 10m_Sprint   1.831333 B
5  2019-06-10    Athlete2 10m_Sprint   2.026667 B
6  2019-06-17    Athlete1 Broad_Jump 191.500000 A
7  2019-06-17    Athlete2 Broad_Jump 200.666667 B
8  2019-06-17 Athlete3 10m_Sprint   1.803667 B
9  2019-06-17    Athlete2 10m_Sprint   2.090000 B
10 2019-06-24    Athlete1 Broad_Jump 192.000000 A

R Script for Rendering RMarkdown

WT <- read.csv("WT.csv")
for (hub in unique(WT$Hub)){
  subgroup <- subset(WT, Hub == hub)
  render("Hub_Test.rmd",output_file = paste0('report.', hub, '.pdf'))   
}

RMarkdown File (Hub_Test.rmd):

WT <- read.csv("WT.csv")

for (hub in unique(WT$Hub)){
  subgroup <- subset(WT, Hub == hub)
}
summary(subgroup)

This set up creates 2 PDFs in my working directory with ONLY A data. I must be missing something.

Upvotes: 1

Views: 751

Answers (1)

heds1
heds1

Reputation: 3448

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}

WT <- structure(list(Athlete = structure(2:1, .Label = c("Athlete2", "Athlete1"
), class = "factor"), Test = structure(2:1, .Label = c("10m_Sprint", 
"Broad_Jump"), class = "factor"), Hub = structure(2:1, .Label = c("A", 
"B"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))

subgroup <- subset(WT, Hub == hub)
summary(subgroup)
```

generation script

library(rmarkdown)

NWT <- structure(list(Athlete = structure(2:1, .Label = c("Athlete2", "Athlete1"
), class = "factor"), Test = structure(2:1, .Label = c("10m_Sprint", 
"Broad_Jump"), class = "factor"), Hub = structure(2:1, .Label = c("A", 
"B"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))

for (hub in unique(WT$Hub)){
  subgroup <- subset(WT, Hub == hub)
  render("Hub_Test.rmd",output_file = paste0('report.', hub, '.html'))   
}

Upvotes: 1

Related Questions