In one of my packages I use the .onAttach
hook to run some R code and then use assign
to make the value available as one of the package variables. I do it because variable
depends on the content of some file, which can change between one session and the other. The code I use is 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 not possible to do something like MyRPackage::variable
(unless I have already attached the package with library(MyRpackage)
.
I know this is because I should put that code in the .onLoad
hook, however I can't make the assignment so that it works.
I have 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"))
}
but both of them fail with some error when I run MyRPackage:::variable
without using library
to attach the package.
What is the correct to do the assignment in the .onLoad hook?
some_function
so that you can callMyRPackage::some_function()
? – BinkMyRPackage:::variable
without loading the package before because thevariable
is assigned only when you actually load the package. Something I don't understand? – Meningitis