.First.lib idiom in R packages

I see the following idiom in the .First.lib function in many 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 starts when the package loads.

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

+4
source share
2 answers

Such an idiom is antiques. Packages must have namespaces and use .onLoad, .onUnload and .onAttach. For instance:

 .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") } 

For a business with a call, the lazyLoad function is best avoided by simply adding this to the DESCRIPTION file:

 LazyLoad: true 
+11
source

You ask why it searches for .First.Lib when the script deleted it before. lazyLoad loads the database from R objects, which in the above code are loaded into the myEnv environment. It is possible that a set of objects loaded into this environment contains .First.Lib , and it is this code that is looking for. Indeed, I assume that the goal was only to run .First.Lib , which was stored in the loaded database of objects.

Another common idiom in packages without NAMESPACE is (from the vegan package):

 .First.lib <- function(lib, pkg) { library.dynam("vegan", pkg, lib) packageStartupMessage("This is vegan ", utils::packageDescription("vegan", field="Version"), appendLF = TRUE) } 

Loads the compiled code, ready for use, and prints a simple startup message with the package name and version number. This is in keeping with the .onLoad response of @Romain, but without NAMESPACE.

+3
source

All Articles