How to clearly define a set of variables when loading the R package and clear them when unloading?

I would like the color set to be determined when the package is loaded and cleared when the package is disconnected.

What I came up with seems to work as shown in the following toy example, which relies on deep appropriation (which I know is 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, the graph works (seq (1: 4, col = C.1). Is there a better or more elegant or less potentially destructive way to implement this?

+6
source share
2 answers

Which seems to work the way I want:

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

.onAttach <- function(libname, pkgname) {
  .registerColors()
}

, ( ), , , , .

, .

0

. , , , .

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

plot(1:4, col=chooseCols())
+5

Source: https://habr.com/ru/post/1017364/


All Articles