我如何使我的R疗程成为香草? [英] How can I make my R session vanilla?

查看:90
本文介绍了我如何使我的R疗程成为香草?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对先前问题的澄清,R --vanilla启动R时获得的内容.例如,我想编写一个不受特定用户的自定义设置影响的脚本.

我特别想要以下内容

  • 不读取R历史记录,配置文件或环境文件
  • 不会从以前的会话中重新加载数据或对象

help("vanilla")不会返回任何内容,而且我对自定义设置的范围还不够熟悉,无法知道如何摆脱所有设置.

有没有办法进入新的香草环境? (?new.env似乎没有帮助)

解决方案

您不仅可以使当前会话变为香草,还可以像这样从R内开始一个新的香草R会话

> .Last <- function() system("R --vanilla")
> q("no")


我认为使用上述方法可能会遇到问题,因为在R重新启动后,脚本的其余部分将无法执行.使用以下代码,R将在退出前运行.Last. .Last将告诉它重新启动,而不读取站点文件或环境文件,也不会打印启动消息.重新启动后,它将运行您的代码(以及执行其他一些清理操作).

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") 

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") 

这篇关于我如何使我的R疗程成为香草?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆