有没有办法在R中检索哈希映射的键?

时间:2017-09-27 12:41:42

标签: r hashmap

我是R

中Hashing算法的新手

我在R中有一个hashmap,如下所示:

set.seed(123)
HH <- hashmap(LETTERS, rnorm(26))

我正在尝试获取特定值的密钥。有办法吗?

1 个答案:

答案 0 :(得分:1)

R具有本地哈希表实现,其性能可与其他基于包的方法媲美(请参阅https://blog.dominodatalab.com/a-quick-benchmark-of-hashtable-implementations-in-r/进行比较)。

这是您的示例,

set.seed( 123 );
#' create hash table
HH <- new.env( hash = TRUE );

#' assign() for setting each key value pair (one key:value pair at a time, hence mapply())
mapply(FUN = function(key,value){ assign(key, value, env = HH) }, LETTERS, rnorm(26));

#' given a key, get() returns a single value
get( "A", env = HH );

#' given a vector of keys, mget() returns a list of values
mget( c("B", "C", "D"), env = HH );

#' exists() is handy for querying a hash table for pre-existing key:value pairs
if(!exists("AA", env = HH)){
  assign("AA", runif(1), env = HH)
}