我想生成大量报告。为简单起见,假设我想创建5个小的pdf文档,只有一个简单的标题循环通过名称向量。
\documentclass[12pt]{article}
\newcommand{\dsfrac}[2]{\frac{\displaystyle #1}{\displaystyle #2}}
\author{Me}
\title{\Sexpr{print(namelist)}}
\maketitle
\end{document}
我如何开始循环生成这些报告:
namelist <- c("Tom","Dick","Harry","John","Jacob")
提前致谢!
PS:奖励积分,用于向我展示如何定义生成的PDF文档的名称。
答案 0 :(得分:7)
您可以在循环中调用Sweave
,如下所示。
# Create the template file, "test.Rnw"
template <- "test.Rnw"
cat("
\\documentclass{article}
\\title{\\Sexpr{namelist[i]}}
\\begin{document}
\\maketitle
\\end{document}
", file=template)
# Parameters
namelist <- c("Tom","Dick","Harry","John","Jacob")
# Main loop: just compile the file,
# it will use the current value of the loop variable "i".
for(i in 1:length(namelist)) {
Rnw_file <- paste("test_", i, ".Rnw", sep="")
TeX_file <- paste("test_", i, ".tex", sep="")
file.copy(template, Rnw_file)
Sweave(Rnw_file)
system(paste("pdflatex --interaction=nonstopmode", TeX_file))
}
答案 1 :(得分:5)
我更喜欢使用brew
+ Sweave/knitr
来执行此类模板。这是我的方法:
# CREATE A BREW TEMPLATE ON FILE: template.brew
\documentclass[12pt]{article}
\newcommand{\dsfrac}[2]{\frac{\displaystyle #1}{\displaystyle #2}}
\author{Me}
\title{<%= title %>}
\begin{document}
\maketitle
\end{document}
# FUNCTION TO BREW AND WEAVE TEMPLATE TO PDF
gen_pdf <- function(title){
rnw_file <- sprintf("%s.rnw", title)
tex_file <- sprintf("%s.tex", title)
brew('template.brew', rnw_file)
Sweave(rnw_file)
tools::texi2pdf(tex_file, clean = TRUE, quiet = TRUE)
unlink(c(rnw_file, tex_file))
}
# GENERATING THE PDF FILES
namelist <- c("Tom","Dick","Harry","John","Jacob")
plyr::l_ply(namelist, gen_pdf, .progress = 'text')