2012-01-05 160 views
4

我想生成大量報告。爲了簡單起見,假設我想創建5個小的pdf文檔,只有一個簡單的標題可以循環使用一個名稱向量。使用Sweave動態生成PDF報告

\documentclass[12pt]{article} 
\newcommand{\dsfrac}[2]{\frac{\displaystyle #1}{\displaystyle #2}} 
\author{Me} 
\title{\Sexpr{print(namelist)}} 
\maketitle 
\end{document} 

我怎麼會去通過這些報告生成的循環:

​​

提前感謝!

PS:用於向我顯示如何定義生成的PDF文檔名稱的獎勵分數。

回答

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)) 
} 
+0

謝謝文森特,我對Sweave的熟悉程度不夠,引起了一陣拉發。 – 2012-01-05 11:33:06

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') 
+0

我不確定我瞭解<%= title %>如何被向量名稱列表中的元素替換,但在我的真實生活情況中,我需要添加大約20或30個數據點,包括數字 - 我不確定我可以看到我將如何擴展這一點。 'l_ply'的有趣用法。 – 2012-01-05 12:59:09

+1

'<%= title %>'是'brew'語法,當您衝煮模板時會解析該語法。如果您可以在文檔的'variable'元素上發佈更多細節,我可以幫助設置正確的'brew'模板。 – Ramnath 2012-01-05 15:32:19

+0

有幾張圖片是動態生成的(ggplot),其餘的只是數字被分流到位。 – 2012-01-06 11:42:24