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

别来无恙 提交于 2019-11-29 02:52:16

问题


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] ="

回答1:


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




回答2:


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" 



回答3:


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.



来源:https://stackoverflow.com/questions/7804816/how-to-create-a-dictionary-hash-table-by-iterating-through-a-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!