Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between .Rprofile and .First

Tags:

r

This might be straightforward, but I still feel frustrated, so I'd appreciate some quick explanation. I have extensively looked for a proper answer, but cannot seem to find one.

Since my .Rprofile includes all the commands that I need to run every time I open Rstudio (or R in general), why do I have the optionality to define the .First() function within the .Rprofile? What is it really the purpose of .First()?

To give an example, suppose that my .Rprofile has the following lines:

.First <- function(){
  library(xts)
  cat("\nWelcome at", date(), "\n") 
}

How different is the above from simply having in my .Rprofile the lines:

library(xts)
cat("\nWelcome at", date(), "\n") 

I have tried both and they do have the same outcome.

Thanks!

like image 508
Nick Baltas Avatar asked Jul 05 '13 08:07

Nick Baltas


People also ask

Where is the .rprofile file?

Rprofile files live in the base of the user's home directory, and project-level . Rprofile files live in the base of the project directory. R will source only one . Rprofile file.

What is customized startup?

Customizing the startup environment allows you to set R options, specify a working directory, load commonly used packages, load user-written functions, set a default CRAN download site, and perform any number of housekeeping tasks. You can customize the R environment through either a site initialization file (Rprofile.

Where are R profiles saved?

Rprofile file is found in C:\Program Files\R\R-3.4.


1 Answers

The main difference is that .First is executed after the default workspace image .Rdata (if it exists) is loaded, and so has access to objects in that workspace.

For example, let's create an object that will be automatically loaded on startup:

x <- 2
save.image()

Quit R, and create a .RProfile in your default working directory containing:

y <- try(print(x))
print(y)
.First <- function()
{
    print(x)
    invisible(NULL)
}

The first attempt to print x should fail, but the second should succeed.

like image 177
Hong Ooi Avatar answered Sep 22 '22 15:09

Hong Ooi