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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With