Detect if an R session is run in RStudio at startu

2019-02-20 03:47发布

问题:

This question already has an answer here:

  • Check if R is running in RStudio 9 answers

I use R both in the terminal and in RStudio (on mac and linux) and wonder if it is possible to use different .Rprofiles for the two, or preferably use the same base .Rprofile but source different environment specific tweak scripts.

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

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.

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.

回答1:

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
}