Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Sweave or knitr with objects from existing R session

Tags:

r

knitr

sweave

Suppose I have an object x in my current session:

x <- 1

How can I use this object in an Sweave or knitr document, without having to assign it explicitly:

\documentclass{article}
\begin{document}
<<>>=
  print(x)
@
\end{document}

Reason I am asking is because I want to write an R script that imports data and then produces a report for each subject using an Sweave template.

like image 779
Sacha Epskamp Avatar asked Dec 08 '11 16:12

Sacha Epskamp


2 Answers

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))
like image 104
Ramnath Avatar answered Oct 21 '22 15:10

Ramnath


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.

like image 22
Aaron left Stack Overflow Avatar answered Oct 21 '22 14:10

Aaron left Stack Overflow