How can I make my R session vanilla?

我只是一个虾纸丫 提交于 2019-12-03 08:40:48

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!