This is a follow up for clarification of a previous question, How can I ensure a consistent R environment among different users on the same server?
I'd like to enter a "vanilla" R session from within R, e.g. similar to what I would obtain if I launched R using the command R --vanilla
. For example, I would like to write a script that is not confounded by a particular user's custom settings.
In particular, I'd like the following
- doesn't read R history, profile, or environment files
- doesn't reload data or objects from previous sessions
help("vanilla")
does not return anything, and I am not familiar enough with the scope of custom settings to know how to get out of all of them.
Is there a way to enter new, vanilla environment? (?new.env
does not seem to help)
You can't just make your current session vanilla, but you can start a fresh vanilla R session from within R like this
> .Last <- function() system("R --vanilla")
> q("no")
I think you'll probably run into a problem using the above as is because after R restarts, the rest of your script will not execute. With the following code, R will run .Last
before it quits. .Last
will tell it to restart without reading the site file or environment file, and without printing startup messages. Upon restarting, it will run your code (as well as doing some other cleanup).
wd <- getwd()
setwd(tempdir())
assign(".First", function() {
#require("yourPackage")
file.remove(".RData") # already been loaded
rm(".Last", pos=.GlobalEnv) #otherwise, won't be able to quit R without it restarting
setwd(wd)
## Add your code here
message("my code is running.\n")
}, pos=.GlobalEnv)
assign(".Last", function() {
system("R --no-site-file --no-environ --quiet")
}, pos=.GlobalEnv)
save.image() # so we can load it back when R restarts
q("no")
IMHO, reproducible research and interactive sessions don't go well together. You should consider writing executable scripts called from the command line, not from an opened interactive session. At the top of the script, add --vanilla
to the shebang:
#!/path/to/Rscript --vanilla
If your script needs to read inputs (arguments or options), you can use ?commandArgs
or one of the two packages getopt
or optparse
for parsing them from the command line.
If the user really needs to do his own work in an interactive session, then he can still do so and call your script via system()
: your script will still use its own vanilla session. There's just a little extra work around passing inputs and outputs.