From simon.urbanek at r-project.org  Thu Mar 11 15:54:51 2010
From: simon.urbanek at r-project.org (Simon Urbanek)
Date: Thu, 11 Mar 2010 09:54:51 -0500
Subject: [Rd] Associative array?
In-Reply-To: <20100311075212.66a6a0e7.misc7@emerose.org>
References: <20100311075212.66a6a0e7.misc7@emerose.org>
Message-ID: <85602218-8121-4893-A262-86EC56E75002@r-project.org>

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



[Rd] Associative array?
Simon Urbanek