Using external data from within another package
This article is originally published at https://logfc.wordpress.com
If you make the error which I did, you will try to use the data (say, “pckgdata”) from another package (say, “pckg”) naively like this:
someFunc <- function() { data(pckgdata) foo <- pckgdata$whatever }
This will result in an error:
someFunc: no visible binding for global variable ‘pckgdata’ someFunc : <anonymous>: no visible binding for global variable ‘pckgdata’ Undefined global functions or variables: pckgdata
Here is the solution (thanks to the comments from stackexchange:
.myenv <- new.env(parent=emptyenv()) someFunc <- function() { data("pckgdata", package="pckg", envir=".myenv") foo <- .myenv$pckgdata$whatever }
Actually, let us load the object as soon as our package is loaded:
.myenv <- new.env(parent=emptyenv()) .onLoad <- function(libname, pkgname){ data("pckgdata", package="pckg", envir=".myenv") } someFunc <- function() { foo <- .myenv$pckgdata$whatever }
Now any of the functions in our package can use the pckgdata
, whenever. Note that we want to use .onLoad()
, and not .onAttach()
— the latter one is for such things as startup messages when the package is manually attached by the user.
Alternatively, you can create your environment within the function itself:
<br />someFunc <- function() { myenv <- new.env(parent=emptyenv()) data("pckgdata", package="pckg", envir="myenv") foo <- .myenv$pckgdata$whatever }
Thanks for visiting r-craft.org
This article is originally published at https://logfc.wordpress.com
Please visit source website for post related comments.