Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R list as key for hash

Tags:

hashmap

r

vector

I am using the hash library and would like to use a vector as the key, however, it wants to assign to each of the values in the vector, but I want to use the vector itself as the key. How can I set and access the hash elements to achieve this? I would like to do something like this:

library(hash)
h <- hash()

inc <- function(key) {
  if(has.key(c(key), h)) {
    h[[key]] = h[[key]] + 1
  } else {
    h[[key]] = 1
  }
}

inc(c('a', 'b'))

And have the key c('a', 'b') and value 1 in the hash. Whenever I pass the same vector, then the value is increased by one.

I understand this is a normal behavior in R since it is an array programming language, but I would like to avoid it in this case.

like image 249
brancz Avatar asked Jul 31 '15 11:07

brancz


1 Answers

Here's an idea: you can use deparse() to produce an unambiguous string representation of the input argument, which will be a valid hash key. Theoretically this could work on any R object, not just atomic vectors.

library(hash);
h <- hash();

hinc <- function(key.obj) { key.str <- deparse(key.obj); h[[key.str]] <- if (has.key(key.str,h)) h[[key.str]]+1 else 1; };
hget <- function(key.obj) { key.str <- deparse(key.obj); h[[key.str]]; };

x1 <- c('a','b');
x2 <- 'ab';
hinc(x1);
hinc(x1);
hinc(x2);

hget(x1);
## [1] 2
hget(x2);
## [1] 1
like image 142
bgoldst Avatar answered Oct 02 '22 08:10

bgoldst