Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start a new R session in knitr

Tags:

r

knitr

How can I start a new R session in knitr? I would rather start a new session rather than use something like rm(list=ls()) because it is not equivalent.

<<myname>>=
#some R code
@
<<another_chunk>>=
#start a new R session
#more R code
@
like image 529
Xu Wang Avatar asked Apr 06 '12 04:04

Xu Wang


2 Answers

Okay, now I have something more substantial for you, inspired by an answer on the R-help list by Georg Ruß. He suggest three things to get R back to how it was at start up, I've written this six step manual for you.

First, you save a string of the packages you have running at start up (this should be done before anything else, before you run any other code),

foo <- .packages()

Second, when you want to reset R, as you also mention, you run

rm(list=ls()) 

to remove all objects. Then, third, you run,

bar <- .packages()

to get a string of current packages. Followed by,

foobar <- setdiff(bar, foo)

Fifth, you remove the difference with this work-around loop,

toRemove <- paste("package:", foobar, sep='') 
#or paste0("package:", foobar) in R-2.15.0 or higher
for(i in seq_along(foobar)) {           
    detach(toRemove[i], character.only=TRUE)    
}

Sixth, depending on your setup, you source your .Rprofile

source(".Rprofile")

This should put R into the state it was in when you started it. I could have overlooked something.

like image 152
Eric Fail Avatar answered Oct 25 '22 02:10

Eric Fail


Instead of starting a new R session in knitr, I would recommend you just to start a new R session in your terminal (or command window) like this:

R -e "library(knitr); knit('your_input.Rnw')"

If you are under Windows, you have to put the bin directory of R into your environment variable PATH (I'm very tired of describing how to do this, so google it by yourself if you are in the Windows world, or see the LyX Sweave manual).

However, most editors do start a new R session when calling Sweave or knitr, e.g. LyX and RStudio, etc. You can find more possible editors in http://yihui.name/knitr/demo/editors/ I do not really see the need to call R -e ... in the terminal.

like image 25
Yihui Xie Avatar answered Oct 25 '22 02:10

Yihui Xie