【发布时间】:2018-03-04 15:27:11
【问题描述】:
我有几个数据集,每个数据集都有一个共同的分组因素。我想为每个分组因素生成一个包含单独部分的大型报告。因此,我想为分组因子的每次迭代重新运行一组rmarkdown 代码。
使用here 的以下方法对我不起作用。即:
---
title: "Untitled"
author: "Author"
output: html_document
---
```{r, results='asis'}
for (i in 1:2){
cat('\n')
cat("#This is a heading for ", i, "\n")
hist(cars[,i])
cat('\n')
}
```
因为我想在每个分组因素上运行的降价并不容易适合一个代码块。报告必须按分组因子排序,我希望能够在分组因子的每次迭代中进出代码块。
所以我去调用 Rmd. 并使用 Rscript 中的循环为每个分组因子进行渲染,如发现 here:
# run a markdown file to summarise each one.
for(each_group in the_groups){
render("/Users/path/xx.Rmd",
output_format = "pdf_document",
output_file = paste0(each_group,"_report_", Sys.Date(),".pdf"),
output_dir = "/Users/path/folder")
}
我的计划是然后将各个报告与pdftk 合并。但是,当我进行第 5 次迭代时,我的 Rstudio 会话挂起并最终因致命错误而中止。我已经单独运行了Rmd.,以了解它停止工作的分组因素。
我用以下简单的测试文件测试了一些循环:
.R
# load packages
library(knitr)
library(markdown)
library(rmarkdown)
# use first 5 rows of mtcars as example data
mtcars <- mtcars[1:5,]
# for each type of car in the data create a report
# these reports are saved in output_dir with the name specified by output_file
for (car in rep(unique(rownames(mtcars)), 100)){
# for pdf reports
rmarkdown::render(input = "/Users/xx/Desktop/2.Rmd",
output_format = "pdf_document",
output_file = paste("test_report_", car, Sys.Date(), ".pdf", sep=''),
output_dir = "/Users/xx/Desktop")
}
.Rmd
```{r, include = FALSE}
# packages
library(knitr)
library(markdown)
library(rmarkdown)
library(tidyr)
library(dplyr)
library(ggplot2)
```
```{r}
# limit data to car name that is currently specified by the loop
cars <- mtcars[rownames(mtcars)==car,]
# create example data for each car
x <- sample(1:10, 1)
cars <- do.call("rbind", replicate(x, cars, simplify = FALSE))
# create hypotheical lat and lon for each row in cars
cars$lat <- sapply(rownames(cars), function(x) round(runif(1, 30, 46), 3))
cars$lon <- sapply(rownames(cars), function(x) round(runif(1, -115, -80),3))
cars
```
Today is `r Sys.Date()`.
```{r}
# data table of cars sold
table <- xtable(cars[,c(1:2, 12:13)])
print(table, type="latex", comment = FALSE)
```
这很好用。因此,我还查看了在Rmd. 上运行我的实际循环时的内存压力,它变得非常高。
- 有没有办法在循环调用
Rmd.文件时减少内存? - 有没有比循环调用
Rmd.文件更好的方法来为多个分组因素创建报告,该文件不依赖于整个循环位于一个代码块中?
【问题讨论】:
标签: r knitr r-markdown