equivalent of a python dict in R

前端 未结 3 657
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 00:46

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] =          


        
相关标签:
3条回答
  • 2021-01-31 01:28

    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"
    
    0 讨论(0)
  • 2021-01-31 01:37

    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

    0 讨论(0)
  • 2021-01-31 01:49

    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.

    0 讨论(0)
提交回复
热议问题