Reputation: 4239
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
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
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
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