Reputation: 111
I am working on an R package right now that includes example images that can be used. I want to set it up so the paths to those images are stored in a global variable that can be accessed either by loading the package or by using something like myPackage::myVar
.
Currently, I have the images in the inst/media
folder and set variables containing their paths in the .onLoad
function in my zzz.R
file; the function looks like this:
.onLoad = function(libname, pkgname) {
dog = system.file("media", "dog.png", package="myPackage")
assign("dog", dog, envir=parent.env(environment()))
}
When I load my package with devtools::load_all()
, I can access the variable with just dog
. However, when I build with devtools::build()
and install manually, I can only access the variable with myPackage:::dog
.
Further, I have an example in my man pages generated with roxygen that uses the following code:
ret = parsePath(dog)
When I run devtools::check()
it returns an error with this warning saying Error : object dog not found
.
Is there any way that I can add this global variable in a way that allows me to access them by loading the package and typing the name, and allows the examples to run without error during R CMD check?
Upvotes: 0
Views: 283
Reputation: 111
The issue was that while the dog
variable was being assigned to the environment, it was not being exported by the package; the solution is to export the variable as described in this post.
The variable is first assigned to the environment with the .onLoad
function:
.onLoad = function(libname, pkgname) {
dog = system.file("media", "dog.png", package=pkgname)
assign("dog", dog, envir=parent.env(environment()))
}
Then in a separate file, the variable is exported in quotes like such:
#' @name dog
#' @title The path to an image of a Dog
#' @export
"dog"
I also had to manually add export(dog)
to the NAMESPACE file before roxygen did it automatically for me. This allows the variable to be accessed by myPackage::dog
. Without exporting the variable in quotes, the variable could only be accessed with myPackage:::dog
and would not be seen by other functions using just dog
. This also passes devtools::check
.
Upvotes: 0