这是对前一个问题进行澄清的后续工作,如何确保同一服务器上不同用户之间的R环境一致?
我想从R中进入一个"vanilla"R会话,例如类似于我使用命令启动R时所获得的会话R --vanilla.例如,我想编写一个不受特定用户自定义设置混淆的脚本.
特别是,我想要以下内容
help("vanilla") 不返回任何内容,我对自定义设置的范围不熟悉,知道如何摆脱所有这些设置.
有没有办法进入新的香草环境?(?new.env似乎没有帮助)
恕我直言,可重复的研究和互动会议并不顺利.您应该考虑编写从命令行调用的可执行脚本,而不是从打开的交互式会话编写.在脚本的顶部,添加--vanilla到shebang:
#!/path/to/Rscript --vanilla
Run Code Online (Sandbox Code Playgroud)
如果脚本需要读取输入(参数或选项),则可以使用?commandArgs这两个包中的一个getopt或optparse从命令行解析它们.
如果用户确实需要在交互式会话中完成自己的工作,那么他仍然可以通过system()以下方式调用您的脚本:您的脚本仍将使用自己的vanilla会话.传递输入和输出只需要一些额外的工作.
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")
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)