Reputation: 382
I am trying to build a package that extends another package. However at its most basic level I am doing something wrong. I build a simple example that presents the same issue:
I have two packages, packageA
and packageB
. packageA
has a single R file in the R folder that reads:
local.env.A <- new.env()
setVal <- function()
{
local.env.A$test <- 1
}
getVal <- function()
{
if(!exists("test", envir = local.env.A)) stop("test does not exist")
return(local.env.A$test)
}
For packageB I have the following single R file in the R folder:
# refers to package A
setVal()
getValinA <- function()
{
return(getVal())
}
I want both packageA
and packageB
to be available for end users, therefore I set packageB to depend on packageA
(in the description file). When packageB
is loaded, e.g. by means of library(packageB)
I expect it to run setVal()
and thus set the test value. However, if I next try to get the value that was set by means of getValinA()
, it throws me the stop:
> library(packageB)
Loading required package: PackageA
> getValinA()
Error in getVal() : test does not exist
I am pretty sure it is related to environments, but I am not sure how. Please help!
Upvotes: 0
Views: 27
Reputation: 382
With thanks to @Roland. The answer was very simple. I was under the impression (assumptions assumptions assumptions!) that when you perform library(packageB)
it would load all the actions within it, in my case perform the setVal()
function. This is however not the case. If you wish this function to be performed you need to place this within the function .onLoad:
.onLoad <- function(libname, pkgname)
{
setVal()
}
By convention you place this .onload
function in an R file called zzz.R
. Reason being that if you do not specifically collate your R scripts it will load alphabetically, and it makes sense to perform your actions when at least all the functions in your package are loaded.
Upvotes: 2