如何在 R 环境中迭代哈希项?
我正在尝试找到一种在 R 中使用哈希映射的方法,经过一番搜索后我得到了 R 环境。 但如何迭代环境中的所有项目呢? 当我运行以下代码时,我期待这样的输出:
1
2
但我得到两行 NULL,我怎样才能得到我想要的结果?
map <- new.env(hash=T, parent=emptyenv())
assign('a', 1, map)
assign('b', 2, map)
for (v in ls(map)) {
print(map$v)
}
I'm trying to find a way to use a hash map in R, and after some searching I get the R-environment.
But how can I iterate through all the items in an environment ?
When I run the following code, I was expecting output like this :
1
2
But I get two lines of NULL instead, how can I get what I want ?
map <- new.env(hash=T, parent=emptyenv())
assign('a', 1, map)
assign('b', 2, map)
for (v in ls(map)) {
print(map$v)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在需要解释输入的函数内使用“$”是编程错误的常见来源。请改用表单 object[[value]] (不带引号。)
The use of "$" inside a function where it is desired to interpret the input is a common source of programming error. Use instead the form object[[value]] (without the quotes.)
这取决于你想做什么。我假设您上面的
print
示例只是作为示例而执行的操作,但您可能想做的不仅仅是打印!如果您想根据环境的每个元素获取一个对象,那么您可以使用
eapply(env, function)
。它的工作方式与其他*apply()
函数类似。它返回一个列表,其中的对象是您从传递给 eapply() 的函数创建的对象,其名称是从环境复制过来的。例如,在您的特定情况下,
返回两个元素的列表。它看起来很像哈希表,表明您可以将哈希表实现为列表而不是环境(这有点不正统,但绝对有趣)。
要了解这对于某些重要的自定义函数如何工作,这里有一个示例
如果您想为环境的每个元素执行某些操作,而不在最后返回列表对象,你应该像 @DWin 在他的回答中那样使用 for 循环。
不过,我担心的是,您实际上并不想只是打印,而是最终会根据“哈希表”元素创建对象,然后将它们放回列表中以供进一步处理。在这种情况下,您确实应该使用
eapply()
。代码将更加简洁,并且将更紧密地遵循 R 的习惯用法。它负责为您迭代和创建结果列表。It depends on what you want to do. I am assuming that your
print
example above is something that you are doing just as an example but that you may want to do something more than just print!If you want to get an object based on each element of an environment, then you use
eapply(env, function)
. It works like the other*apply()
functions. It returns a list whose objects are the objects you created from the function passed toeapply()
and whose names are copied over from the environment.For example, in your specific case
returns a list of the two elements. It looks a lot like a hash table showing that you could implement a hash table as a list instead of an environment (which is a little unorthodox, but definitely interesting).
To see how this would work for some non-trivial, custom function, here is an example
If you instead want to do something for each of the elements of an environment, without returning a list object at the end, you should use a for loop like @DWin did in his answer.
My worry, though, is that you will not really want to just print but that you will eventually create objects based on your "hash table" elements and then stuff them back into a list for further processing. In that instance, you should really use
eapply()
. The code will be cleaner and it will more closely adhere to R's idioms. It takes care of iterating and creating the list of results for you.