检测 R 会话是否在启动时在 RStudio 中运行 [英] Detect if an R session is run in RStudio at startup
问题描述
我在终端和 RStudio(在 mac 和 linux 上)都使用 R,想知道是否可以为两者使用不同的 .Rprofile
,或者最好使用相同的基础 .Rprofile
但来源不同的环境特定调整脚本.
I use R both in the terminal and in RStudio (on mac and linux) and wonder if it is possible to use different .Rprofile
s for the two, or preferably use the same base .Rprofile
but source different environment specific tweak scripts.
我认为将以下代码放在我的 .Rprofile
中会起作用,但不幸的是 session_info
在 .First
时未设置> 正在运行.Sys.getenv
也不是.
I thought it would work to place the following code in my .Rprofile
, but unfortunately session_info
isn't set at the time .First
is run. Neither is 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 ...
和任何使用其他命令行参数的脚本.
I also tried setting alias R='R --args terminal'
in .bash_profile
which does allow me to detect if the session was started from bash, but it screws up R CMD ...
and any script that uses other command line arguments.
我意识到可能无法从 R 会话中检测到它从哪里开始,但也许 RStudio 中有一些我不知道的聪明选项.
I realise it might not be possible to detect from within an R session where it was started from, but perhaps there is some clever option in RStudio I am not aware of.
推荐答案
您可以通过检查 RSTUDIO
环境变量的值来检测 RStudio 是否正在托管 R 会话.例如,
You can detect whether RStudio is hosting the R session by checking for the value of the RSTUDIO
environment variable. For example,
if (!is.na(Sys.getenv("RSTUDIO", unset = NA))) {
# RStudio specific code
}
这篇关于检测 R 会话是否在启动时在 RStudio 中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!