假设x我当前会话中有一个对象:
x <- 1
Run Code Online (Sandbox Code Playgroud)
如何在Sweave或knitr文档中使用此对象,而无需明确指定它:
\documentclass{article}
\begin{document}
<<>>=
print(x)
@
\end{document}
Run Code Online (Sandbox Code Playgroud)
我问的原因是因为我想写一个R脚本导入数据,然后使用Sweave模板为每个主题生成一个报告.
Ram*_*ath 20
我会采用稍微不同的方法,因为使用全局变量会减少reproducibility分析.我用brew+ sweave/knitr来实现这个目标.这是一个简单的例子.
# brew template: "template.brew"
\documentclass{article}
\begin{document}
<<>>=
print(<%= x %>)
@
\end{document}
# function to write report
write_report <- function(x){
rnw_file <- sprintf('file_%s.rnw', x)
brew::brew('template.brew', rnw_file)
Sweave(rnw_file)
tex_file <- sprintf('file_%s.tex', x)
tools::texi2pdf(tex_file, clean = TRUE, quiet = TRUE)
}
# produce reports
dat <- 1:10
plyr::l_ply(dat, function(x) write_report(x))
Run Code Online (Sandbox Code Playgroud)
我认为它只是有效.如果您的Sweave文件名为"temp.Rnw",则运行
> x <- 5
> Sweave("temp.Rnw")
Run Code Online (Sandbox Code Playgroud)
您必须担心正确命名结果输出,以便不会覆盖每个报告.
在评估R代码块时,Sweave和knitr利用全局环境(请参阅参考资料globalenv()),因此您的全局环境中的任何内容都可用于您的文档.(严格地说,knitr使用父帧parent.frame(),其是globalenv()在大多数情况下)
| 归档时间: |
|
| 查看次数: |
5474 次 |
| 最近记录: |