How to iterate through hash items, in an R environment?

岁酱吖の 提交于 2019-12-02 21:11:44

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

for (v in ls(map)) {
    print(map[[v]])
}

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 to eapply() and whose names are copied over from the environment.

For example, in your specific case

map <- new.env(hash=T, parent=emptyenv())  
assign('a', 1, map)  
assign('b', 2, map)  

eapply(map, identity)

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

eapply(map, function(e) {
  # e here stands for a copy of an element of the environment
  e <- my.function(e)
  my.other.function(e)
})

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.

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