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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With