[R] Data Frame as Hash Table

Don MacQueen macq at llnl.gov
Mon May 31 06:31:48 CEST 2010


If you only need a single variable (in this case value), and just 
want to refer to it by the "key", there are other options.

    value <- rnorm(6)
    names(value) <- format(seq(0.5,3,0.5))

     value['1.5']

But do watch out for numerical precision in the output of seq() if 
your vector of values is long.

Or, given the dataframe version, it's not essential to assign key to 
the row names

   d[ d$key==1.5 , ]
or
   subset(d , key==1.5)

(again with some potential for numerical precision issues)

If you want your psuedo-hash-table to reference more complex 
structures, use a list.

   myhash <- vector('list',6)   ## initialize a list of six elements
   names(myhash) <- letters[1:6]     ## name the six elements
   myhash$a <- data.frame(x=1:4, y=c('a','b','d','f'))   ## assign 
something to the first element
   myhash$b <- rnorm(10)       ## assign something to the second element
and so on for $c, $d, $e, and $f
.... the elements don't even have to have the same structure

-Don

At 1:03 AM -0700 5/30/10, Alan Lue wrote:
>I'm interested in using a data frame as if it were a hash table.  For
>instance if I had the following,
>
>>  (d <- data.frame(key=seq(0.5, 3, 0.5), value=rnorm(6)))
>   key        value
>1 0.5 -1.118665122
>2 1.0  0.465122921
>3 1.5 -0.529239211
>4 2.0 -0.147324638
>5 2.5 -1.531503795
>6 3.0 -0.002720434
>
>Then I'd like to be able to quickly retrieve the "value" of "key" 1.5
>to get -0.53.  How would one go about doing this?
>
>Yours,
>Alan Lue
>
>______________________________________________
>R-help at r-project.org mailing list
>https://*stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://*www.*R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.


-- 
---------------------------------
Don MacQueen
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062
macq at llnl.gov



More information about the R-help mailing list