equivalent of a python dict in R

user1357015 picture user1357015 · May 21, 2012 · Viewed 64.6k times · Source

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, i don't "Do Stuff". Atom_Count is an integer.

Thanks!

Answer

joran picture joran · May 21, 2012

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.