Search code examples
rrstudiorprofile

Content of the .First function does not appear to be processed when running in RStudio


In my .Rprofile I've defined the following .First function that has two purposes:

  • Show available library paths
  • Change the settings of colorout package if running RStudio with a bright theme

    .First <- function() {
        if (interactive()) {
           cat(
             "\nProcessed RProfile at:",
             date(),
             "\n",
             "Available libraries",
             "\n",
             paste(.libPaths(), collapse = "\n "),
             "\n"
             )
    
        # Check if running bright theme and adjust colour settings
        if (assertive::is_rstudio()) {
            theme_info <- rstudioapi::getThemeInfo()
            if (!theme_info$dark) {
                colorout::setOutputColors(
                    normal = 2,
                    negnum = 3,
                    zero = 3,
                    number = 3,
                    date = 3,
                    string = 6,
                    const = 5,
                    false = 5,
                    true = 2,
                    infinite = 5,
                    index = 2,
                    stderror = 4,
                    warn = c(1, 0, 1),
                    error = c(1, 7),
                    verbose = TRUE,
                    zero.limit = NA
                )
           }
        }
      }
    }
    

Problem

When running in the terminal the function returns the desired results: enter image description here

However, the content that would be generated by the .First function does not show:

enter image description here

also the colour settings do not seem to apply. When I source and call the function as .First() then it works with no problems.

I want to understand what is different about RStudio start-up that it does not produce equivalent results to R session running in the terminal and accessing same .Rprofile?


Solution

  • Well for one thing, the entire body of the function is wrapped in if(interactive()){}. The interactive function will return TRUE and therefore the code will run when you run your function from the command line. But when .First is run automatically at startup, the interactive function returns FALSE and the entire body of the function is skipped.

    It looks like when a session starts to be interactive may differ in the RStudio startup compared to Rterm. You can test this by putting code like this at the beginning of .First:

    if(interactive()) {
      cat('Interactive is TRUE\n')
    } else {
      cat('Interactive is FALSE\n')
    }