I have a data frame of two columns: key and value and I would like to create a dictionary using the respective row of each column for each element of the dictionary / hash t
It appears to me you've gotten some misinformation. I'm not even certain where you get the idea of that syntax for creating a hashtable.
In any case: for hashtable-like functionality, you may want to consider using an environment
: these work internally with a hashtable (if I remember correctly), so do quite what you want to.
You would use this something like:
someenv<-new.env()
someenv[["key"]]<-value
Given your data.frame
, something like this would fill it up:
for(i in seq(nrow(lbls)))
{
someenv[[ lbls[i,1] ]]<- lbls[i,2]
}
(note: this requires that the first column is an actual character column, not a factor!!)
You can then easily get to a named value by using someenv[["nameofinterest"]]
.
The easiest way is to change names
after creating variables. So you can define a function like this:
cc <- function(name, value) {
ret <- c(value)
names(ret) <- name
ret
}
cc(c(letters[1:2], "a name"), c(LETTERS[1:2], "a value"))
# output like this
# a b a name
# "A" "B" "a value"
Another option that is similar to what you've seen with Python or Perl is the hash
package. See: http://cran.r-project.org/web/packages/hash/
If your keys are particularly long, then I recommend storing two hash tables. First, hash the key, using the digest
package and store a dictionary (hash table) that maps from digest to key (mapping from key to digest is already done by the digest
package ;-)), and then from the digest to the value that you wish to store. This works very well for me.