How do I use a map in R?

I am working on a map data structure in which I need to store a pair of key values.

 map[key1]<-value1
 map[key2]<-value2
 map[key3]<-value3
 map[key4]<-value4

      

I need to get a value based on a key. How can I implement this in R?

+3


source to share


2 answers


Use a list, because a simple vector constructed with c

cannot 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 is it failing? because map

now:

> map
key11 key12 key13  key2  key3 
    1     2     3     2     3 

      

use list

instead:



> map = list(key1 = c(1,2,3), key2 = 2, key3 = 3)
> map[["key1"]]
[1] 1 2 3

      

also dynamically expandable:

> map[["key99"]]="Hello You!"
> map
$key1
[1] 1 2 3

$key2
[1] 2

$key3
[1] 3

$key99
[1] "Hello You!"

      

Start blank map=list()

if you are creating one.

+9


source


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 

      

+1


source







All Articles