Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cleanly define a set of variables when an R package loads and clear them on unload?

Tags:

r

r-package

I would like to have a set of colors become defined when a package loads and cleared when package detaches.

What I've come up with that seems to work is shown in the following toy example which relies on deep assignment (which I know to be evil)

.onLoad <- function(libname, pkgname) {

}

.registerColors <- function(){
  C.1 <<- c("#FF0000FF", "#80FF00FF", "#00FFFFFF", "#8000FFFF")
  C.2 <<- c("#00AAFFFF", "#0000FFFF", "#AA00FFFF", "#FF00AAFF")
}

.onUnload <- function(libpath){
}
.onAttach <- function(libname, pkgname) {
  .registerColors()
  packageStartupMessage("Welcome to XYZ")
}

.onDetach <- function(libname, pkgname) {
  rm(C.1, C.2, pos = 1)
  packageStartupMessage("Buh-bye")
}

In this case, plot(seq(1:4, col = C.1) works. Is there a better or more elegant or less potentially destructive way to implement this?

like image 730
Avraham Avatar asked May 18 '17 19:05

Avraham


1 Answers

You don't really need to go to all that trouble. Just define a function that checks if the package is loaded, and returns the appropriate colours.

chooseCols <- function()
{
    if("this_package" %in% search())
        C.1
    else # use default colours
}

plot(1:4, col=chooseCols())
like image 170
Hong Ooi Avatar answered Nov 20 '22 08:11

Hong Ooi