Динамическая генерация PDF-отчетов с Sweave - PullRequest
4 голосов
/ 05 января 2012

Я хотел бы создать большое количество отчетов. Для простоты, скажем, я хочу создать 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-документов.

Ответы [ 2 ]

7 голосов
/ 05 января 2012

Вы можете просто вызвать 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))
}
5 голосов
/ 05 января 2012

Я предпочитаю использовать 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')
...