Skip to content
Prev 1164 / 12125 Next

[R-pkg-devel] environment scoping

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