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