Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ESS & Knitr/Sweave: How to source the Rnw file into an interactive session?

This is a terribly simple request, and I can't believe I haven't found the solution to this yet, but I've been searching for it far and wide without luck.

I have an .Rnw file loaded up in Emacs, I use M-n s to compile it. Everything works well, and it even opens an R buffer. Great. But that buffer is entirely useless: it doesn't contain the objects that I just sourced!

Example minimal .Rnw file:

\documentclass{article}
\begin{document}
<<>>=
  foo <- "bar"
@
\end{document}

Using M-n s, I now have a new R-buffer with a session loaded up, but:

> foo
Error: object 'foo' not found 

That is disappointing. I would like to play around with the data interactively. How do I achieve that? I don't want to be sourcing the file line-by-line, or region-by-region with C-c C-c or something similar every time I change my code. Ideally, it should be just like RStudio's source function, that leaves me with a fully prepared R session.

I haven't tried this with sweave yet, only with knitr.

EDIT: the eval=TRUE chunk option does not seem to result in the correct behaviour.

like image 955
Aleksandar Dimitrov Avatar asked Sep 07 '13 12:09

Aleksandar Dimitrov


2 Answers

This behaviour was recently changed in ESS. Now sweave and knitr are executed directly in the global environment, as if when you write it yourself at command line. So wait for a couple of more weeks till ESSv13.09 is out or use the development version.

Alternatively, you can also set ess-swv-processing-command to "%s(%s)" and you will get the same result, except automatic library loading.

For the record, knitr (in contrast to sweave) evaluates everything in it's own environment unless you instruct it otherwise.

[edit: Something went wrong. I don't see the correct .ess_weave any more. Probably some git commit messup again. So it is not fixed in 13.09. Fixing it now. Sorry.]

like image 162
VitoshKa Avatar answered Nov 14 '22 23:11

VitoshKa


Open an interactive R session, and then call Sweave directly, I believe like this (untested though). knitr works in the same way, though you need to load the knitr library first.

> Sweave("yourfile.Rnw")

There is some potential for peril here, though. If you call Sweave in a session after doing other things, your code can use things previously in the workspace, thus making your results unreproducible.

like image 24
Aaron left Stack Overflow Avatar answered Nov 15 '22 01:11

Aaron left Stack Overflow