2

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.

juvchan
  • 6,113
  • 2
  • 22
  • 35
Backlin
  • 14,612
  • 2
  • 49
  • 81
  • You could do something like `if (!is.na(Sys.getenv("RSTUDIO", unset = NA)) { ... }`; RStudio will always set the `RSTUDIO` environment variable upon launch. – Kevin Ushey Mar 14 '16 at 22:37
  • @KevinUshey Thank you so much! It works brilliantly. If you add it as an answer I'll accept it right away. – Backlin Mar 15 '16 at 14:37

1 Answers1

9

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
}
Kevin Ushey
  • 20,530
  • 5
  • 56
  • 88