相当于 R 中的一条蟒蛇

我想在 R 中做一个相当于 python dict 的东西,基本上在 python 中,我有:

visited = {}


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

这里的思想是,如果我看到特定的 atom _ count,就得到了 visited[atom_count] = 1。因此,如果我再次看到 atom _ count,那么我不会“ Do Stuff”。Atom_Count是一个整数。

谢谢!

87792 次浏览

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.

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

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"