4

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 ?

3
  • ?hash says "Keys must be a valid R name, must be a character vector and must not be the empty string, ‘""’." Numbers are not generally considered valid R names. Commented Aug 5, 2013 at 20:16
  • 1
    I saw that. That is why I converted the vector y using as.character. But i did is.character(y), which returned TRUE. Commented Aug 5, 2013 at 20:23
  • 1
    Being character is a necessary, but not sufficient condition for being a valid R name. See R commands; case sensitivity etc. in the introductory manual. Commented Aug 5, 2013 at 20:31

3 Answers 3

2
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
Sign up to request clarification or add additional context in comments.

2 Comments

that's the same as mine :)
I was 30 seconds earlier :)
2

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

7 Comments

that's same as mine :)
I was 30 seconds later :)
should I use a hash or a list, if I have a data vector which is 2^16 long. I may quick access to different their indicies ????
what is in each of these 2^16 elements? Are they uniform, will a matrix or array suffice? If so, use that. The question is what is the specific need for hash? 2^16 is not a reason.
actually, what i meant was that i need to have 2^16 entries / names. And each contain an integer. I will need to access different entries and change their values from time to time
|
0

Using setNames works:

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

Another option might be to use the memoise package.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.