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)
}
Use #each to iterate over a hash.
UPDATE: It turns out, R has a perfectly performant hash table implementation, it's just not intuitively named or easy to find. If you create a new environment using new. env(hash=TRUE) , R provides you an environment that performs admirably.
Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element. Let us see how we can use the each method to display the restaurant menu.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With