mynameisJEFF
mynameisJEFF

Reputation: 4239

how to access integer keys in R using R package 'hash'

I want to build a hash in R. I installed the hash package in R.

I need to have integer keys. However, I cannot access them .

> y <- as.character(seq(0,10,1))
> y
 [1] "0"  "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

> h <- hash(key =y, values = 1:11)
> h
<hash> containing 2 key-value pair(s).
  key : 0  1  2  3  4  5  6  7  8  9  10
  values :  1  2  3  4  5  6  7  8  9 10 11

When I try to access the keys, it gave me a value of NULL.

> h[["0"]]
NULL

 h$"0"
NULL
> h$0
Error: unexpected numeric constant in "h$0"

Is there a solution to this ?

Upvotes: 4

Views: 1451

Answers (3)

Metrics
Metrics

Reputation: 15458

library(hash)    
h <- hash(y, 1:11)
> h[["0"]]
    [1] 1
> h["0"]
<hash> containing 1 key-value pair(s).
  0 : 1
> h$"0"
[1] 1

Upvotes: 2

Ricardo Saporta
Ricardo Saporta

Reputation: 55420

You can use

 h <- hash(y, 1:11)

 h[["2"]]
 [1] 3

However, I would just use a named list. Why the need for the hash package?

 h <- as.list(1:11)
 names(h) <- y
 h[["2"]]
 [1] 3

Upvotes: 2

Karsten W.
Karsten W.

Reputation: 18500

Using setNames works:

h <- hash(setNames(1:11, 0:10))
h[["0"]]

Another option might be to use the memoise package.

Upvotes: 0

Related Questions