Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent of a python dict in R

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!

like image 290
user1357015 Avatar asked May 21 '12 02:05

user1357015


People also ask

Is there a dictionary equivalent in R?

Overview. Dict is a R package which implements a key-value dictionary data structure based on R6 class. It is designed to be similar usages with other languages' dictionary implementations (e.g. Python). R's vector and list , of course can have names, so you can get and set value by a name (key) like a dictionary.

Can you compare Dicts in Python?

You can use the == operator, and it will work. However, when you have specific needs, things become harder. The reason is, Python has no built-in feature allowing us to: compare two dictionaries and check how many pairs are equal.

Can you append to a dict in Python?

To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.


2 Answers

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.

like image 68
joran Avatar answered Nov 05 '22 19:11

joran


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" 
like image 20
user2739472 Avatar answered Nov 05 '22 19:11

user2739472