Reputation: 3521
I am working on map data structure in which i need to store key value pair.
map[key1]<-value1
map[key2]<-value2
map[key3]<-value3
map[key4]<-value4
I need to get value based on key. How can i implement this in R?
Upvotes: 3
Views: 1986
Reputation: 94202
Use a list, because a simple vector constructed with c
can't handle anything more than scalar values:
> map = c(key1 = c(1,2,3), key2 = 2, key3 = 3)
> map[["key1"]]
Error in map[["key1"]] : subscript out of bounds
why does this fail? because map
is now:
> map
key11 key12 key13 key2 key3
1 2 3 2 3
use a list
instead:
> map = list(key1 = c(1,2,3), key2 = 2, key3 = 3)
> map[["key1"]]
[1] 1 2 3
also dynamically extensible:
> map[["key99"]]="Hello You!"
> map
$key1
[1] 1 2 3
$key2
[1] 2
$key3
[1] 3
$key99
[1] "Hello You!"
Start with an empty map=list()
if you are building one up.
Upvotes: 8
Reputation: 60944
You can use a named vector:
map = c(key1 = 1, key2 = 2, key3 = 3)
map[["key1"]]
And you can easily add new ones:
map[["key4"]] = 4
> map
key1 key2 key3 key4
1 2 3 4
Upvotes: 0