[R] Hash table...

Philipp Pagel p.pagel at wzw.tum.de
Thu Apr 14 10:48:48 CEST 2011

On Thu, Apr 14, 2011 at 06:44:53PM +1200, Worik R wrote:
> To improve the efficiency of a process I am writing I would like to cache
> results.  So I would like a data structure like a hash table.
> So if I call Z <- f(Y)  I can cache Z associated with Y: CACHE[Y] <- Z
> I am stumped.  I expected to be able to use a list for this but I cannot
> figure how....

If y is an integer, factor or string you could try something along these

cache <- list()
y <- 12
cache[[as.character(y)]] <- sqrt(y)
cache[[as.character(y)]] <- sqrt(y)

[1] 3.464102

[1] 9.899495

Of course this can get you in trouble if y is a floating point
number because of the issues with "identity" of such numbers, as
discussed in ?all.equal and FAQ 7.31 "Why doesn't R think these
numbers are equal?".


Dr. Philipp Pagel
Lehrstuhl für Genomorientierte Bioinformatik
Technische Universität München
Wissenschaftszentrum Weihenstephan
Maximus-von-Imhof-Forum 3
85354 Freising, Germany

More information about the R-help mailing list