Dynamically generate PDF reports with Sweave

I would like to create a large number of reports. For simplicity, suppose I want to create 5 small pdf documents with a simple heading that cycles through the name vector.

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

How will I cycle through the generation of these reports for:

 namelist <- c("Tom","Dick","Harry","John","Jacob") 

Thanks in advance!

PS: Bonus points for showing me how to determine the name of the received PDF documents.

+4
source share
2 answers

You can simply invoke Sweave in a loop as shown below.

 # 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)) } 
+7
source

I prefer to use brew + Sweave/knitr to create this type of pattern. Here is my approach:

 # 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') 
+5
source

Source: https://habr.com/ru/post/1389406/


All Articles