我正在研究地图数据结构,我需要存储键值对.
map[key1]<-value1
map[key2]<-value2
map[key3]<-value3
map[key4]<-value4
Run Code Online (Sandbox Code Playgroud)
我需要根据关键获得价值.我怎样才能在R中实现这个?
使用列表,因为构造的简单向量c不能处理除标量值以外的任何内容:
> map = c(key1 = c(1,2,3), key2 = 2, key3 = 3)
> map[["key1"]]
Error in map[["key1"]] : subscript out of bounds
Run Code Online (Sandbox Code Playgroud)
为什么这会失败?因为map现在:
> map
key11 key12 key13 key2 key3
1 2 3 2 3
Run Code Online (Sandbox Code Playgroud)
用一个list代替:
> map = list(key1 = c(1,2,3), key2 = 2, key3 = 3)
> map[["key1"]]
[1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
也是动态可扩展的:
> map[["key99"]]="Hello You!"
> map
$key1
[1] 1 2 3
$key2
[1] 2
$key3
[1] 3
$key99
[1] "Hello You!"
Run Code Online (Sandbox Code Playgroud)
map=list()如果要构建一个空的,请从空开始.
| 归档时间: |
|
| 查看次数: |
1686 次 |
| 最近记录: |