On 27/10/2016 10:05 AM, Glenn Schultz 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?

You're writing in R-package-devel, so I'll assume you're thinking of doing this in a package that you will release to others.

In that case, the downside is huge. The global environment doesn't belong to you, it belongs to the user. If you choose to write to it, you could clobber something there that the user doesn't want clobbered. You'll hopefully get warnings from "R CMD check" about doing this, and CRAN will not accept your package.

There are a couple of ways to do what you want. The simplest is to have the function that creates the common data return it in some sort of structure, and you pass that structure to other functions that need to work with it. You can use S3 or S4 or other class systems to mark the structure for what it is.

Another approach that works sometimes is to have the function that creates the common data also create functions to work on it, and return them. Since functions created in another function can see its local variables (even after it has returned!), those functions will have access to the common data, and nobody else will (without going through some contortions). Some of the newer object systems support this approach, but you don't need to use them, you can just return a function (or a list of functions) and make calls to it/them.

I hope this helps.

Duncan Murdoch

______________________________________________
R-package-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-package-devel

Reply via email to