equivalent of a python dict in R

PythonRDictionary

Python Problem Overview


I want to make the equivalent of a python dict in R. Basically in python, I have:

visited = {}

if atom_count not in visited:
  Do stuff
  visited[atom_count] = 1

The idea is, if I saw that specific, atom_count, I have visited[atom_count] = 1. Thus, if I see that atom_count again, then I don't "Do Stuff". Atom_Count is an integer.

Thanks!

Python Solutions


Solution 1 - Python

The closest thing to a python dict in R is simply a list. Like most R data types, lists can have a names attribute that can allow lists to act like a set of name-value pairs:

> l <- list(a = 1,b = "foo",c = 1:5)
> l
$a
[1] 1

$b
[1] "foo"

$c
[1] 1 2 3 4 5

> l[['c']]
[1] 1 2 3 4 5
> l[['b']]
[1] "foo"

Now for the usual disclaimer: they are not exactly the same; there will be differences. So you will be inviting disappointment to try to literally use lists exactly the way you might use a dict in python.

Solution 2 - Python

If, like in your case, you just want your "dictionary" to store values of the same type, you can simply use a vector, and name each element.

> l <- c(a = 1, b = 7, f = 2)
> l
a b f 
1 7 2

If you want to access the "keys", use names.

> names(l)
[1] "a" "b" "f"

Solution 3 - Python

I believe that the use of a hash table (creating a new environment) may be the solution to your problem. I'd type out how to do this but I just did so yesterday day at talkstats.com.

If your dictionary is large and only two columns then this may be the way to go. Here's the link to the talkstats thread with sample R code:

HASH TABLE LINK

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1357015View Question on Stackoverflow
Solution 1 - PythonjoranView Answer on Stackoverflow
Solution 2 - Pythonuser2739472View Answer on Stackoverflow
Solution 3 - PythonTyler RinkerView Answer on Stackoverflow