Re: [Rd] caching frequently used values

From: Tamas K Papp <tpapp_at_Princeton.EDU>
Date: Wed 13 Dec 2006 - 23:18:40 GMT

On Wed, Dec 13, 2006 at 03:05:46PM -0800, Robert Gentleman wrote:

> e1 = new.env(hash=TRUE)
>
> e1[["1"]] = whateveryouwant
>
> ie. just transform to characters, but I don't see why you want to do
> that - surely there are more informative names to be used -

Because they are derivatives, and best indexed by numbers. I wrote an example to demonstrate what I think the solution is (for memoizing powers of numbers). It works, but I am not an experienced programmer: can you please look at it to check that I do things right and do not abuse any feature of R?

## memoize powers of integers

createpowerlist <- function(n) {
  list(n=n,env=new.env(hash=TRUE))
}

getpower <- function(powerlist,i) {
  iname <- as.character(i)
  if (exists(iname,powerlist$env))
    get(iname,powerlist$env)
  else {

    res <- i^powerlist$n                # result
    assign(iname,res,powerlist$env)
    res
  }
}

cubelist <- createpowerlist(3)

exists("12",cubelist$env)               # FALSE
getpower(cubelist,12)                   # 1728
exists("12",cubelist$env)               # TRUE


Thanks,

Tamas



R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Thu Dec 14 14:52:50 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 14 Dec 2006 - 07:31:01 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.