. First function in R

I do not understand the point. The first function in R. My reason is that any code in .Rprofile will be received and executed when R starts anyway.

this is

.First<-function(){ library('devtools') } 

and this one

 library('devtools') 

in.Rprofile have exactly the same effect.

However, here is an example that shows. The first may matter:

example 1, you can see that X11.options () $ type correctly becomes Xlib, as set in .Rprofile

 >> cat .Rprofile .First <- function() { library(devtools) } setHook( packageEvent("grDevices", "onLoad"), function(...) grDevices::X11.options(type="Xlib") ) >> Rscript -e 'X11.options()$type' [1] "Xlib" 

example 2, you can see that X11.options () $ type is still cairo, setHook in .Rprofile did not take effect

 >> cat .Rprofile library(devtools) setHook( packageEvent("grDevices", "onLoad"), function(...) grDevices::X11.options(type="Xlib") ) >> Rscript -e 'X11.options()$type' [1] "cairo" 
  • In which case I absolutely must use. First function?
  • why. First changed in the example above?

Thanks!

+7
r
source share
2 answers

This may not be necessary, but this is another place to change the startup. It certainly does not hurt to have it.

I usually run R in different directories to keep things separate; link to a common .Rprofile; and use. First adapt your current R startup environment to the specific issue I'm working on. If the first action were not available, I would have to create it.

+1
source share

One of the advantages of placing startup code in .First () instead of .RProfile is that you can use local variables that will not remain in your global environment after completion of .First ().

For example, my.First () displays a list of .R files in the project directory in any number of columns:

 localFiles <- list.files(pattern = "\\.R$", ignore.case = TRUE) maxChars <- max(nchar(localFiles)) numCols <- as.integer((options("width")$width-2) / (1 + maxChars)) # how many columns will fit? fmt <- sprint(" %%-%d", maxChars) # left justified in each column for (nn in localFiles) { if ((match(nn, localFiles) %% numCols) == 1) cat(" ") # indent each row cat(sprint(fmt, nn)) if ((match(nn, localFiles) %% numCols) == 0) cat("\n") # end of row } if (length(localFiles) %% numCols != 0) cat("\n") # end last row if not complete 

Since this is in .First (), all temporary variables are cleared when the function returns and the global environment remains clean.

0
source share

All Articles