Re: [Rd] Associative array?

From: Simon Urbanek <simon.urbanek_at_r-project.org>
Date: Thu, 11 Mar 2010 09:54:51 -0500

Ben,

On Mar 11, 2010, at 8:52 , Ben wrote:

> Hi, can someone tell me how to use associative arrays in R? It can
> be a hashtable or some kind of tree, as long as the lookups aren't
> O(n).
> One way to do this is to use names, e.g. in:
>
> list(a=3, ...)[["a"]]
>
> presumably looking up "a" is very quick. (Can someone tell me
> offhand how that is implemented? Hashtable?)

lists are generic vectors with names so lookup is O(n). Environments in R are true hash tables for that purpose:

 > h=new.env(hash=TRUE)
 > h[["foo"]]="bar"
 > ls(h)

[1] "foo"

> However, if I wanted to, say,
> memoize a numeric function, I can't elegantly use R names because R
> names must be characters.
>

I don't quite understand - characters are (after raw vectors) the most expressive data type, so I'm not quite sure why that would be a limitation .. You can cast anything (but raw vector with nulls) into to a character.

> I found the hash package on CRAN:
>
> http://cran.r-project.org/web/packages/hash/index.html
>
> but it seems the keys are still characters. Also, I haven't heard
> anyone talking about it. Trees and hashtables are common data
> structures, so this problem must come up a lot.
>

I don't see a problem thus I'm not surprised it didn't come up ;). But maybe I'm just missing your point ...

Cheers,
Simon



R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Thu 11 Mar 2010 - 15:03:27 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 12 Mar 2010 - 07:41:04 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.

list of date sections of archive