start a new R session in knitr

knitr, r

Solution

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.

Problem

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 @ ```

Original source