我想生成大量报告.为简单起见,假设我想创建5个小的pdf文档,只有一个简单的标题循环通过名称向量.
\documentclass[12pt]{article}
\newcommand{\dsfrac}[2]{\frac{\displaystyle #1}{\displaystyle #2}}
\author{Me}
\title{\Sexpr{print(namelist)}}
\maketitle
\end{document}
Run Code Online (Sandbox Code Playgroud)
我将如何通过生成这些报告来循环:
namelist <- c("Tom","Dick","Harry","John","Jacob")
Run Code Online (Sandbox Code Playgroud)
提前致谢!
PS:奖励积分,用于向我展示如何定义生成的PDF文档的名称.
您可以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))
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢用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')
Run Code Online (Sandbox Code Playgroud)