Reputation: 123
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!
Upvotes: 9
Views: 736
Reputation: 57686
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.
Upvotes: 14