[R-pkg-devel] environment scoping

Jenny Bryan jenny at stat.ubc.ca
Thu Oct 27 16:55:36 CEST 2016


Hi Glenn,

It sounds like you should create an environment for your package. If you store these objects in the global environment, they are exposed to the user and, more importantly, user could modify or delete them. If you use an environment specific to your package, you can be sure you are the only one messing with them.

You create it like so:

.package_env <- new.env(parent = emptyenv())

And read from / write into it like so (very much like a list):

.package_env$foo <- ...
.package_env$foo

or with assign() and get():

assign(foo, bar, envir = .package_env)
get(foo, envir = .package_env)

This blog post by Jeff Allen is a nice write-up of what you're trying to do:

http://trestletech.com/2013/04/package-wide-variablescache-in-r-package/

-- Jenny

> On Oct 27, 2016, at 7:05 AM, Glenn Schultz <glennmschultz at me.com> wrote:
> 
> All,
> 
> I would like to have some inputs available to many functions.  For example, I have coefficient for a term structure fit which I would like to make a available to total return functions.  Thereby eliminating the need to fit the same term structure over and over again.  However, I still reading and researching scoping.  My understanding is that I could fit the term structure and keep the coefficients in the global environment which would then make those coefficients available to all functions requiring a term structure object input.  Am I correct in my understanding.  What is the downside of environment global, if any?
> 
> Best Regards,
> Glenn
> ______________________________________________
> R-package-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-package-devel



More information about the R-package-devel mailing list