Run Sweave or knitr with objects from existing R session

谁都会走 提交于 2019-11-27 07:09:00

I think it just works. If your Sweave file is named "temp.Rnw", just run

> x <- 5
> Sweave("temp.Rnw")

You'll have to worry about naming the resulting output properly so each report doesn't get overwritten.

I would take a slightly different approach to this, since using global variables reduces the reproducibility of the analysis. I use brew + sweave/knitr to achieve this. Here is a simple example.

# 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))

Both Sweave and knitr makes use of the global environment (see globalenv()) when evaluating R code chunks, so whatever in your global environment can be used for your document. (Strictly speaking, knitr uses the parent frame parent.frame() which is globalenv() in most cases)

Another option I have used in the past is to have the Sweave code open a file,

in my R session

write.csv(x, "tabletoberead.csv")

in my sweave document

<<label=label, echo=FALSE>>= 
datatobeused<-read.csv("tabletoberead.csv")
...more manipulations on data ....
@ 

Obviously you should include code to stop if the file can't be found.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!