我想知道是否有一种简单的方法可以在knitr
. 我知道的唯一方法是:(从https://github.com/yihui/knitr-examples/blob/master/075-knit-expand.Rnw简化)。但是将输出收集到src
然后在循环之后打印它是一个拖累,因为我想编写一个函数来从任意数据集产生这样的循环。
\documentclass{article}
\title{Using knit\_expand() for templates}
\author{Yihui Xie}
\begin{document}
\maketitle
\tableofcontents
<<lm-mtcars, tidy.opts=list(width.cutoff=55)>>=
# the template
tpl = c("\\subsection{Regression on {{xvar}}}",
"<<lm-{{xvar}}>>=",
"lm(mpg~{{xvar}}, data=mtcars)",
"@")
# expand to knitr source and pass to knit()
src = lapply(names(mtcars)[-1], function(xvar) {knit_expand(text = tpl)})
@
\Sexpr{knit(text = unlist(src))}
\end{document}
所以我希望能够做的是这样的事情:
\documentclass{article}
\title{Using knit\_expand() for templates}
\author{Yihui Xie}
\begin{document}
\maketitle
\tableofcontents
<<lm, tidy.opts=list(width.cutoff=55)>>=
myLfFun=function(dataset){
... some function definition which produces say an lm for each variable in dataset ...
}
@
\Sexpr{myLfFun(Titanic}
...
\Sexpr{myLfFun(mtcars}
... etc
\end{document}
...如果我在其上运行 brew() 会产生...
\documentclass{article}
\title{Brew + knitR}
\author{Ramnath Vaidyanathan}
\begin{document}
\maketitle
\tableofcontents
<<lm-cyl >>=
lm(mpg ~ cyl, data = mtcars)
@
<<lm-disp >>=
lm(mpg ~ disp, data = mtcars)
@
<<lm-hp >>=
lm(mpg ~ hp, data = mtcars)
@
<<lm-drat >>=
lm(mpg ~ drat, data = mtcars)
@
<<lm-wt >>=
lm(mpg ~ wt, data = mtcars)
@
<<lm-qsec >>=
lm(mpg ~ qsec, data = mtcars)
@
<<lm-vs >>=
lm(mpg ~ vs, data = mtcars)
@
<<lm-am >>=
lm(mpg ~ am, data = mtcars)
@
<<lm-gear >>=
lm(mpg ~ gear, data = mtcars)
@
<<lm-carb >>=
lm(mpg ~ carb, data = mtcars)
@
((... same for Titanic database ...))
\end{document}
...然后我可以 knit2pdf() 的输出。所以如果模板被称为 tmpl.Rnw,我会运行 brew('tmpl.Rnw','doc.Rnw');knit2pdf('doc.Rnw)