Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.First.lib idiom in R packages

Tags:

package

r

I see the following idiom in the .First.lib function in a lot of R packages:

fullName <- paste("package", pkgname, sep=":")
myEnv <- as.environment(match(fullName, search()))
barepackage <- sub("([^-]+)_.*", "\\1", pkgname)
dbbase <- file.path(libname, pkgname, "R", barepackage)
rm(.First.lib, envir = myEnv)
lazyLoad(dbbase, myEnv)
if(exists(".First.lib", envir = myEnv, inherits = FALSE)) {
    f <- get(".First.lib", envir = myEnv, inherits = FALSE)
    if(is.function(f))
        f(libname, pkgname)
    else
        stop(gettextf("package '%s' has a non-function '.First.lib'",
                      pkgname),
             domain = NA)
}

I understand that the .First.lib function is run when a package is loaded.

I understand that the code above defines an environment for the package and sets up a path, but I don't understand why it's looking for a .First.lib function after it explicitly deletes the .First.lib function. What makes the above idiom so common? Is it a "best practice" to include this in an R package?

like image 859
JD Long Avatar asked Dec 10 '22 12:12

JD Long


1 Answers

That kind of idiom is antique. Packages should have namespaces and use .onLoad, .onUnload and .onAttach. For example:

.onLoad <- function(libname, pkgname){
     # do whatever needs to be done when the package is loaded
     # some people use it to bombard users with 
     # messages using 
     packageStartupMessage( "my package is so cool" )
     packageStartupMessage( "so I will print these lines each time you load it")
}

The whold business with the calling the lazyLoad function is best avoided by just adding this to the DESCRIPTION file:

LazyLoad: true
like image 73
Romain Francois Avatar answered Dec 12 '22 01:12

Romain Francois