Search code examples
rdictionaryhashtable

How to create a dictionary / hash table by iterating through a column?


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 table.

As far as I understand the typical way of using R dictionaries / hash tables is by doing something similar to this.

labels.dic <- c("Id of the item and some other description" = "id")

This works perfectly fine but when I try to do it using the values from the data frame (named lbls in the example) it does not work. Why does this happen?

labels.dic <- c(lbls[1,1]=lbls[1,2])
Error: unexpected '=' in "c(lbls[1,1] ="

Solution

  • 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"]].