Jimmy Lee
Jimmy Lee

Reputation: 117

How to retrieve the name of key by its value from a hash table in R

I have created a hash table as following

require(hash)
h <-  hash( key=letters, number=1:26 )
h
# <hash> containing 2 key-value pair(s).
#   key : a b c d e f g h i j k l m n o p q r s t u v w x y z
#   number :  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
has.key("a", h)
#     a 
# FALSE 

As demonstrated, I couldn't get the result "key" by has.key("a", h)

I have made a bad example for my question. Sorry!! The following is what I want to know...

> h <-  hash("a" = c('apple', 'appear', 'axe'), "b" = c('bear', 'boy', 'box'), "c" = c('car', 'camp', 'colour'))
> h
<hash> containing 3 key-value pair(s).
  a : apple  appear axe   
  b : bear boy  box 
  c : car    camp   colour
> h
<hash> containing 3 key-value pair(s).
  a : apple  appear axe   
  b : bear boy  box 
  c : car    camp   colour
> has.key("apple", h)
apple 
FALSE 

Your answer is appreciated. Thank you very much!!

Upvotes: 0

Views: 51

Answers (2)

Jimmy Lee
Jimmy Lee

Reputation: 117

Thank you for anyone's help. I think this is the answer to my question:

> h <-  hash("a" = c('apple', 'appear', 'axe'), "b" = c('bear', 'boy', 'box'), "c" = c('car', 'camp', 'colour'))
> h
<hash> containing 3 key-value pair(s).
  a : apple  appear axe   
  b : bear boy  box 
  c : car    camp   colour
> invert(h)[["apple"]]
[1] "a"

Upvotes: 1

thothal
thothal

Reputation: 20409

Try

h <-  hash(keys = letters, values = 1:26)
has.key("a", h)
#    a 
# TRUE 

Upvotes: 1

Related Questions