R as a key for the hash

I use the hash library and would like to use the vector as a key, however, it wants to assign each of the values โ€‹โ€‹in the vector, but I want to use the vector itself as a key. How can I set and access 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 enter the key c('a', 'b') and the value 1 in the hash. Whenever I pass the same vector, the value is incremented by one.

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

+6
source share
2 answers

Here is the idea: you can use deparse() to get an unambiguous string representation of the input argument, which will be a valid hash deparse() theory, this can 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 
+2
source

I created an R package called dict that allows you to use vectors as keys:

 library(dict) d <- dict() d[[ c("a", "b") ]] <- 1 d[[ c("a", "b") ]] 

This should be more efficient than disabling objects, as suggested earlier.

0
source

All Articles