R how to make a variable available for namespace at boot time

In one of my packages, I use hook .onAttachto run some R code, and then use assignto make the value available as one of the package variables. I do this because it variabledepends on the contents of some file, which can change between one session and another. The code I use looks like:

.onAttach <- function(libname, pkgname) {
   variable <- some_function()
   assign("variable", variable, envir = as.environment("package:MyRPackage"))
}

When I attach the package with library(MyRpackage), I can use variable.

However, it is impossible to do something like MyRPackage::variable(unless I have already added the package with library(MyRpackage).

I know this because I have to put this code in a hook .onLoad, but I cannot complete the assignment so that it works.

I tried

.onLoad <- function(libname, pkgname) {
   variable <- some_function()
   assign("variable", variable, envir = as.environment("namesoace:MyRPackage"))
}

and

.onLoad <- function(libname, pkgname) {
   variable <- some_function()
   assign("variable", variable, envir = asNamespace("MyRPackage"))
}

, MyRPackage:::variable library .

hook.onLoad?

+4
1

, .onLoad() :

.onLoad <- function(libname, pkgname) {
    variable <- some_function()
    assign("variable", variable, envir = parent.env(environment()))
}

variable MyRPackage:::variable. , some_function(), :

.onLoad <- function(libname, pkgname) {
    variable <- 42
    assign("variable", variable, envir = parent.env(environment()))
}

R

> MyRPackage:::variable
[1] 42

Hadley Wickham Advanced R:

:

...

  • () - .

...

ls() parent.env().

, .onLoad() , :

.onLoad <- function(libname, pkgname) {
    print(environment()) # For demonstration purposes only;
    print(parent.env(environment())) # Don't really do this.
    variable <- 42
    assign("variable", variable, envir = parent.env(environment()))
}

R

<environment: 0x483da88>
<environment: namespace:MyRPackage>

. variable namespace:MyRPackage, assign("variable", variable, envir = namespace:MyRPackage)

: "MyRPackage:

   .nLoad failed loadNamespace() 'MyRPackage', :

  : get (, envir = ns, inherits = FALSE)

  : " "

.

+9

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


All Articles