[Rd] Associative array?

Simon Urbanek simon.urbanek at r-project.org
Thu Mar 11 15:54:51 CET 2010


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



More information about the R-devel mailing list