21

I want to use a dictionary/map data structure in R, similar to Python's dict or C++ STL's std::map or std::hash_map.

I can do all of the following. Is there a difference in their use and/or performance? And if so, which is the best way to have such a data structure in R?

> mm = c()
> mm["my key"] = 10
> mm[["my key"]]
[1] 10
> mm
my key 
    10

> mm = list()
> mm["my key"] = 10
> mm[["my key"]]
[1] 10
> mm
$`my key`
[1] 10

> mm = vector()
> mm["my key"] = 10
> mm[["my key"]]
[1] 10
> mm
my key 
    10 
highBandWidth
  • 16,751
  • 20
  • 84
  • 131
  • 3
    Similar questions have been asked before. Try a StackOverflow search for `[r] hash` and look at the answers. – Andrie Nov 28 '11 at 17:00
  • 2
    Related: [In R, can I use a list as a hash? If so, why is it so slow?](http://stackoverflow.com/questions/3470447/in-r-can-i-use-a-list-as-a-hash-if-so-why-is-it-so-slow) – Joshua Ulrich Nov 28 '11 at 17:03

1 Answers1

23

The fastest will be an environment, since they're hashed by default.

e <- new.env()
e$my_key <- 10
ls(e)
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • 7
    If this is something you want to explore further, this post by the author of R in a Nutshell might be of interest: http://broadcast.oreilly.com/2010/03/lookup-performance-in-r.html – Josh O'Brien Nov 28 '11 at 17:06
  • 3
    Thanks, eventually I decided to use the `hash` package that wraps an environment. – highBandWidth Nov 28 '11 at 19:10