如何通过遍历列创建字典/哈希表? [英] How to create a dictionary / hash table by iterating through a column?

查看:128
本文介绍了如何通过遍历列创建字典/哈希表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个两列的数据框:键和值,我想使用字典/哈希表的每个元素的每列的相应行来创建一个字典。



据了解,使用R字典/哈希表的典型方法是通过做类似的操作。

  labels.dic<  -  c(项目的ID和其他描述=id)

这样做的效果非常好,但是当我尝试使用数据框(在示例中名为 lbls )中的值来执行它时,它不起作用。为什么会发生这种情况?

  labels.dic<  -  c(lbls [1,1] = lbls [1,2] )
错误:c(lbls [1,1] =


解决方案

在我看来,你有一些错误的信息,我甚至不知道在哪里可以得到用于创建哈希表的语法。



在任何情况下:对于类似哈希表的功能,您可能需要考虑使用环境:这些工作内部使用散列表(如果我记得正确),所以做你想要的。



你会使用这样的东西:

  someenv< -new.env()
someenv [[key]]< -value

鉴于您的 data.frame ,这样的东西将填补:

  for(i in seq(nrow(lbls)))
{
someenv [[lbls [i,1]]]< - lbls [i,2 ]
}

(注意:这要求第一列是一个实际的字符列,而不是一个因素!!)



然后可以使用 someenv [[nameofinterest ]]


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

解决方案

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

这篇关于如何通过遍历列创建字典/哈希表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆