Skip to content

Instantly share code, notes, and snippets.

@datalove
Created August 25, 2015 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save datalove/8f201d5888338fd8c90b to your computer and use it in GitHub Desktop.
Save datalove/8f201d5888338fd8c90b to your computer and use it in GitHub Desktop.
Fast lookups using R's evironments, which are implemented using hash tables (vectorised)
# inspired by https://stackoverflow.com/questions/16782518/is-this-a-good-way-to-make-a-multi-dimensional-dictionary-in-r/16782745#16782745
# and http://broadcast.oreilly.com/2010/03/lookup-performance-in-r.html
hash <- function( ) {
new.env( hash = TRUE, parent = emptyenv() )
}
set <- function(key, val, hash) {
invisible(mapply(assign, key, val, MoreArgs = list(envir = hash)))
}
lookup <- function(key, hash, use_names = TRUE) {
sapply(key, get, envir = hash, USE.NAMES = use_names)
}
d = hash()
set(c('a','b'), c(1,2), d)
lookup(c('a','b'), d)
lookup(c('a','b'), d, FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment