Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用swave动态生成PDF报告_R_Latex_Sweave - Fatal编程技术网

R 使用swave动态生成PDF报告

R 使用swave动态生成PDF报告,r,latex,sweave,R,Latex,Sweave,我想生成大量的报告。为了简单起见,假设我想创建5个小的pdf文档,其中只有一个简单的标题,循环使用名称向量 \documentclass[12pt]{article} \newcommand{\dsfrac}[2]{\frac{\displaystyle #1}{\displaystyle #2}} \author{Me} \title{\Sexpr{print(namelist)}} \maketitle \end{document} 我将如何循环生成这些报告: namelist <-

我想生成大量的报告。为了简单起见,假设我想创建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")

namelist您可以在循环中调用
swave
,如下所示

# 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))
}
#创建模板文件“test.Rnw”

模板我更喜欢使用
brew
+
swave/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')
#在文件TEMPLATE.BREW上创建BREW模板
\documentclass[12pt]{article}
\新命令{\dsfrac}[2]{\frac{\displaystyle#1}{\displaystyle#2}
\作者{Me}
\标题{}
\开始{document}
\maketitle
\结束{document}
#函数用于编写模板并将其编织为PDF

gen_pdf感谢Vincent,我对Swave的不熟悉导致了一场令人毛骨悚然的会议。我不确定我是否理解向量名称列表中的元素是如何替换的,但在我的现实生活中,我有大约20或30个数据点需要添加,包括数字-我不确定我能看到如何在此基础上进行扩展。
l\u ply
的有趣用法是
brew
语法,这在
brew
模板时解决。如果您可以发布更多关于文档中
变量
元素的详细信息,我可以帮助您设置正确的
brew
模板。有一些图像是动态生成的(ggplot),其余的只是数字。