[R] Dynamic Dictionary Data Type?

Seth Falcon sfalcon at fhcrc.org
Thu Jun 2 20:59:47 CEST 2005


On  2 Jun 2005, kjetil at acelerate.com wrote:
> The original poster asked for caching of results. here is an example
> using new.env():
>
> memo <- function(fun) {
> mem <- new.env() 
> function(x) {
> if (exists(as.character(x), envir=mem)) get(as.character(x), 
> envir=mem, inherits=FALSE) else {
> val <- fun(x)
> assign(as.character(x), value=val, envir=mem)
> val }
> }
> }
>
>> fib <- memo(function(n) if(n<=1) 1 else fib(n-1)+fib(n-2))
>> system.time( fib(300) )
> [1] 0.01 0.00 0.02   NA   NA
>
> ls(get("mem", env=environment(fib)))
> *output supressed*
>
> To compare:
> system.time( {fib2 <- function(n)if(n<=1)1 else 
> fib2(n-1)+fib2(n-2);fib2(30)})
> [1]  8.07  0.08 12.75    NA    NA
>
>
> (there is (at least) one problem with this solution: if the global 
> workspace contains a
> variable `6`, it gives error. Why?)

Because by default, new.env creates an environment with parent set to
parent.frame().  

So when you call exists, although "6" is not found in the mem
environment, it is found in the global environment.  But then the get
fails.

In terms of using R's environments as dictionary data structures I
think what one wants most of the time is:

myEnv <- new.env(hash=TRUE, parent=NULL)

+ seth




More information about the R-help mailing list