Re: [R] Dynamic Dictionary Data Type?

From: Seth Falcon <sfalcon_at_fhcrc.org>
Date: Fri 03 Jun 2005 - 04:59:47 EST

On 2 Jun 2005, kjetil@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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Fri Jun 03 05:08:07 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:22 EST