Is There a Dictionary Functionality in R
Is There a Way to Create a "Dictionary" in R, Such That It Has Pairs? Something to the Effect of: X=Dictionary(C("Hi","Why","Water"), C(1,5,4)) X["Why"]=5 I'm...
Is there a way to create a "dictionary" in R, such that it has pairs? Something to the effect of:
x=dictionary(c("Hi","Why","water") , c(1,5,4))
x["Why"]=5
I'm asking this because I am actually looking for a two categorial variables function.
So that if x=dictionary(c("a","b"),c(5,2))
x val
1 a 5
2 b 2
I want to compute x1^2+x2 on all combinations of x keys
x1 x2 val1 val2 x1^2+x2
1 a a 5 5 30
2 b a 2 5 9
3 a b 5 2 27
4 b b 2 2 6
And then I want to be able to retrieve the result using x1 and x2. Something to the effect of: get_result["b","a"] = 9
what is the best, efficient way to do this?
6 Answers
I know three R packages for dictionaries: hash, hashmap, and dict.
Update July 2018: a new one, container.
Update September 2018: a new one, collections
Must Read
hash
Keys must be character strings. A value can be any R object.
library(hash)
## hash-2.2.6 provided by Decision Patterns
h <- hash()
# set values
h[["1"]] <- 42
h[["foo"]] <- "bar"
h[["4"]] <- list(a=1, b=2)
# get values
h[["1"]]
## [1] 42
h[["4"]]
## $a
## [1] 1
##
## $b
## [1] 2
h[c("1", "foo")]
## <hash> containing 2 key-value pair(s).
## 1 : 42
## foo : bar
h[["key not here"]]
## NULL
To get keys:
keys(h)
## [1] "1" "4" "foo"
To get values:
values(h)
## $`1`
## [1] 42
##
## $`4`
## $`4`$a
## [1] 1
##
## $`4`$b
## [1] 2
##
##
## $foo
## [1] "bar"
The print instance:
h
## <hash> containing 3 key-value pair(s).
## 1 : 42
## 4 : 1 2
## foo : bar
The values function accepts the arguments of sapply:
values(h, USE.NAMES=FALSE)
## [[1]]
## [1] 42
##
## [[2]]
## [[2]]$a
## [1] 1
##
## [[2]]$b
## [1] 2
##
##
## [[3]]
## [1] "bar"
values(h, keys="4")
## 4
## a 1
## b 2
values(h, keys="4", simplify=FALSE)
## $`4`
## $`4`$a
## [1] 1
##
## $`4`$b
## [1] 2