Reputation: 1457
I am new to R programming. After checking some tutorial I picked up most things I needed, but one thing is still missing: the data structure map.
Does everybody know if R has dict? In which I can store (key, value) pairs?
Thanks!!
Upvotes: 10
Views: 3430
Reputation: 2361
The hash package as aforementioned does add a little overhead but does provide a flexible, intuitive methods for accessing the map/hash/dictionary. It should be very easy for users from another language to grok it.
A list is the best solution if the list has a small number of elements. (<200 or so).
An environment is best to use if you absolutely cannot tolerate a little overhead AND you do not want the flexible, intuitive methods.
The hash package is the best in most situations.
C-
Upvotes: 0
Reputation: 121127
Since array/vector elements can be named, you get some of the properties of a map/dictionary builtin.
x <- c(apple = 1, banana = 99, "oranges and lemons" = 33)
x["apple"]
x[c("bananas", "oranges and lemons")]
x[x == 99]
(If your values are of different types, then you need to use a list
instead of a vector.)
Upvotes: 3
Reputation: 4692
Environments are also a candidate, and in many cases the best option.
e<-new.env(hash=T)
e$a<-1
e$b<-2
R> e$a
[1] 1
The disadvantage of a list is that it is a linear search.
Upvotes: 5
Reputation: 613382
Yes it does and it is called list
.
> x <- list(a=1, b="foo", c=c(1,1,2,3,5))
> x
$a
[1] 1
$b
[1] "foo"
$c
[1] 1 1 2 3 5
In Python it is called dict
, for what it's worth.
Upvotes: 9