有没有办法使用任意类型的值作为环境中的键或 R 中的命名列表?
我一直在寻找 R 中哈希映射的正确实现,其功能类似于 Python 中的映射类型。
经过一些谷歌搜索和搜索 R 文档后,我发现环境和命名列表是我可以使用的唯一选项(真的是这样吗?)。
但两者的问题在于,它们只能将字符作为哈希的关键,甚至不能将数字作为哈希的关键,更不用说其他类型的东西了。
那么有没有办法使用任意的东西作为键呢?或者至少不仅仅是角色。
或者是否有我没有找到具有更好功能的更好的哈希映射实现?
提前致谢。
编辑:
我当前的问题:我需要一张地图来存储数据点之间的距离关系。也就是说,映射的键是一个元组(p1, p2),值是一个数字。
我问一个通用问题而不是具体问题的原因是我最近正在学习 R,我想知道如何操作一些最基本的数据结构,而不仅仅是我的问题所指的内容。所以我将来可能需要使用其他东西作为关键,并且我想避免每次遇到类似的问题时只提出很小的差异。
编辑2:
关于这个话题我得到了很多很好的建议。看来我仍然以Pythonic 的方式思考,而不是应该采用R 的方式。我真的应该得到更多的R-ly!我认为我的目的可以很容易地通过 R 中的矩阵来满足。谢谢大家!
I've been looking for a proper implementation of hash map in R, with functionalities similar to the map type in Python.
After some googling and searching the R documentations, I found that environment and named list are the ONLY options I can use (is that really so?).
But the problem with the two is that they can only take charaters as key for the hashing, not even a number, let alone other type of things.
So is there a way to use arbitrary things as key? or at least more than just characters.
Or is there a better implemtation of hash map that I didn't find with better functionalities ?
Thanks in advance.
Edit:
My current problem: I need a map to store the distance relationship between data points. That is, the key of the map is a tuple (p1, p2) and the value is a number.
The reason I asked a generic question instead of a concrete one is that I'm learning R recently and I want to know how to manipulate some of the most fundamental data structures, not only what my problem refers to. So I may need to use other things as key in the future, and I want to avoid asking similar questions with only minor difference every time I run into them.
Edit 2:
I got a lot of very good advices on this topic. It seems I'm still thinking quite in the Pythonic way, rather than the should-be R way. I should really get more R-ly ! I think my purpose can easily be satisfied by a matrix in R. Thanks All !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
人们不断要求您提供具体示例的原因是,在 Python 中使用哈希表作为适当技术的大多数问题在 R 中都有一个不涉及哈希表的良好解决方案。
也就是说,有时真正的哈希表在 R 中很有用,我建议您查看 hash R 包。它使用环境作为基础,但允许您使用它们进行许多类似 R 的向量工作。它非常高效,而且我从未遇到过任何问题。
请记住,如果您在使用 R 时经常使用哈希表,并且您的代码运行缓慢或有错误,那么您可能可以通过找出更像 R 的方式来实现这一点:)
The reason people keep asking you for a specific example is that most problems for which hash tables are the appropriate technique in Python have a good solution in R that does not involve hash tables.
That said, there are certainly times when a real hash table is useful in R, and I recommend you check out the hash package for R. It uses environments as its base but lets you do a lot of R-like vector work with them. It's efficient and I've never run into a problem with it.
Just keep in mind that if you're using hash tables a lot while working with R and your code is running slowly or is buggy, you may be able to get some mileage from figuring out a more R-like way of doing it :)