How to iterate over hash elements in R environment?

I am trying to find a way to use the hash map in R, and after some searching I get the R environment. But how can I iterate over all the elements in the environment? When I run the following code, I expected output as follows:

1

2

But instead, I get two NULL strings: 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) } 
+6
source share
2 answers

Using "$" inside a function where it is desirable to interpret the input is a common source of programming error. Instead, use the form object [[value]] (without quotation marks.)

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

It depends on what you want to do. I assume that the above print example is what you do as an example, but that you can do something more than just print!

If you want to get an object based on each element of the environment, you use eapply(env, function) . It works like other *apply() functions. It returns a list whose objects are objects that you created from the function passed to eapply() and whose names are copied from the environment.

For example, in your particular case

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

returns a list of two items. It is very similar to a hash table showing that you can implement a hash table as a list instead of an environment (which is a little unorthodox, but definitely interesting).

To find out how this works for some non-trivial user-defined 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 want to do something for each of the elements of the environment without returning the list object at the end, you should use a for loop like @DWin in your answer.

My concern, however, is that you really don't want to just print, but ultimately create objects based on your hash table elements, and then fill them back into the list for further processing. In this case, you really should use eapply() . The code will be cleaner and stick more closely to idioms R. It takes care of iterating and creating a list of results for you.

+7
source

Source: https://habr.com/ru/post/897280/


All Articles