RMarkdown中两个表的循环 - 输出不匹配

时间:2017-11-14 14:09:24

标签: r r-markdown

我正在尝试在RMarkdown中自动化报告,其中我有两个包含不同信息的表,但是有一个共同的站点。我已经写了循环,以便我可以为每个站点生成一个摘要报告,每个表一个,但我无法让其中一个表工作。第一个表始终生成相同的信息,但第二个表对每个唯一站点都是正确的。

我到目前为止使用这篇文章:R Knitr PDF: Is there a posssibility to automatically save PDF reports (generated from .Rmd) through a loop?但我无法让两个循环在同一个文档中打印同一个网站:

R脚本:

set.seed(100)
Site<-c("A","B","C","D","E")
Species<-c("a","b","c","d","e")
Count<-rnorm(40,20,20)
df1<-data.frame(Site,Species,Count)
df1

Habitat<-c("v","w","x","y","z")
Size<-rnorm(40,20,20)
df2<-data.frame(Site,Habitat,Size)
df2

library(tidyverse)
library(rmarkdown)

Habitats<-df2 %>% 
  group_by(Site, Habitat) %>% 
  summarise(Total_Size=sum(Size))
Habitats
report1<-filter(Habitats,Site=='A')
report1

Species<-df1 %>% 
  group_by(Site,Species) %>% 
  summarise(Total_Count=sum(Count))
Species

#Habitats loop, but this bit doesn't work
for(Site in unique(Habitats$Site)){
  subgroup1<-Habitats[Habitats$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}

#Species loop
for(Site in unique(Species$Site)){
  subgroup2<-Species[Species$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}

template.rmd:

```{r, echo=FALSE}
#Report Analysis
Habs<-filter(subgroup1)
Habs
```

```{r, echo=FALSE}
Spp<-filter(subgroup2)
Spp
```

我该怎么做?如果我想使用3个,4个或5个表,所有表都包含与相同站点相关的数据,那么您的解决方案是否也能正常工作?

1 个答案:

答案 0 :(得分:0)

在您的template.rmd中,您正在调用subgroup2

{r, echo=FALSE} Spp<-filter(subgroup2) Spp 但是直到你进入第二个循环才会创建它。

#Species loop
for(Site in unique(Species$Site)){
  subgroup2<-Species[Species$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}

所以当你运行

#Habitats loop, but this bit doesn't work
for(Site in unique(Habitats$Site)){
  subgroup1<-Habitats[Habitats$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}

它还不存在。也许这些方面的东西会有所帮助吗?

for(Site in unique(c(Species$Site,Habitats$Site)){
  subgroup1<-Habitats[Habitats$Site == Site,]
  subgroup2<-Species[Species$Site == Site,]
  render("C:/Users/TVERC/Documents/GIS DataBase/P17-19 National Trust/template.rmd", output_file = paste0('report.', Site, '.html'))
}