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

后端 未结 2 654
無奈伤痛
無奈伤痛 2021-02-03 13:27

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 th

相关标签:
2条回答
  • 2021-02-03 13:42

    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]])
    }
    
    0 讨论(0)
  • 2021-02-03 13:49

    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.

    0 讨论(0)
提交回复
热议问题