【问题标题】:Detect if an R session is run in RStudio at startup [duplicate]检测 R 会话是否在启动时在 RStudio 中运行 [重复]
【发布时间】:2016-06-29 09:39:57
【问题描述】:

我在终端和 RStudio 中(在 mac 和 linux 上)都使用 R,想知道是否可以为两者使用不同的 .Rprofiles,或者最好使用相同的基础 .Rprofile 但源不同的环境特定调整脚本。

我认为将以下代码放在我的.Rprofile 中会起作用,但不幸的是,session_info 在运行.First 时没有设置。 Sys.getenv 也不是。

.First <- function(){
    # [STUFF I ALWAYS WANT TO DO]
    # Load my favourite packages
    # Set CRAN mirror
    # etc. etc.

    # [ENVIRONMENT SPECIFIC TWEAKS]
    if(grepl("RStudio", session_info()$platform$ui)){
        tryCatch(source("~/.R_RStudio"), error=print)
    } else {
        tryCatch(source("~/.R_terminal"), error=print)
    }
}

我还尝试在.bash_profile 中设置alias R='R --args terminal',这确实允许我检测会话是否是从 bash 启动的,但它搞砸了R CMD ... 和任何使用其他命令行参数的脚本。

我意识到可能无法从 R 会话中检测到它的启动位置,但 RStudio 中可能有一些我不知道的聪明选项。

【问题讨论】:

  • 你可以做类似if (!is.na(Sys.getenv("RSTUDIO", unset = NA)) { ... }; RStudio 将始终在启动时设置 RSTUDIO 环境变量。
  • @KevinUshey 非常感谢!它工作得很好。如果您将其添加为答案,我会立即接受。

标签: r session rstudio


【解决方案1】:

您可以通过检查 RSTUDIO 环境变量的值来检测 RStudio 是否正在托管 R 会话。例如,

if (!is.na(Sys.getenv("RSTUDIO", unset = NA))) {
    # RStudio specific code
}

【讨论】:

  • 您的代码缺少右括号:固定版本if (!is.na(Sys.getenv("RSTUDIO", unset = NA))) { # RStudio specific code }
  • 谢谢!我已经编辑了这一点的答案。
猜你喜欢
  • 1970-01-01
  • 2012-09-05
  • 2021-11-08
  • 2015-08-20
  • 1970-01-01
  • 2013-03-18
  • 2011-03-22
  • 2019-04-09
  • 2019-07-17
相关资源
最近更新 更多