[R-pkg-devel] Is there a better way ...?

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Thu Oct 21 14:09:02 CEST 2021


I agree with almost everything Deepayan said, but would add one thing:


On 21/10/2021 3:41 a.m., Deepayan Sarkar wrote:
  ...

> My suggestion is having a package-specific environment, and Duncan's
> is to have a function-specific environment. If you only need this for
> this one function, then that should be good enough. If you eventually
> want to access the persistent information from multiple functions,
> having a package-specific environment would be more useful.

I agree with that statement, but those aren't the only two choices. 
Your local() call can create several functions and return them in a 
list; then just those functions have access to the local variables.  For 
example,

createFns <- local({

    .fooInfo <- NULL

    fn1 <- function (...) { ... }
    fn2 <- function (...) { ... }

    list(fn1 = fn1, fn2 = fn2)
})

fns <- createFns()
fn1 <- fns$fn1
fn2 <- fns$fn2

Now fn1 and fn2 are functions that can see .fooInfo, and nobody else can 
(without going through contortions).

One other difference between this approach and the package-specific 
environment:  there's only one package-specific environment in 
Deepayan's formulation, but I could call createFns() several times, 
creating several pairs of functions, each pair with its own independent 
version of .fooInfo.

I don't know if that's something that would be useful to you, but 
conceivably you'd want to maintain partial plots in several different 
windows, and that would allow you to do so.

And there are other choices too:  there are several packages 
implementing object systems that allow objects to maintain persistent 
data.   I haven't used those, so this list may contain omissions and 
errors:  R6, R.oo, proto.

Duncan Murdoch



More information about the R-package-devel mailing list