[英]Does R have 'dict' as in python or 'map' as in c++ do?
I am new to R programming. 我是R编程的新手。 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? 大家都知道R是否有词典吗? In which I can store (key, value) pairs? 我可以存储(键,值)对吗?
Thanks!! 谢谢!!
Yes it does and it is called list
. 是的,它被称为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. 在Python中,它被称为dict
,因为它的价值。
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. 列表的缺点是它是线性搜索。
有哈希包..
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.) (如果您的值的类型不同,则需要使用list
而不是向量。)
The hash package as aforementioned does add a little overhead but does provide a flexible, intuitive methods for accessing the map/hash/dictionary. 前面提到的散列包确实增加了一些开销,但确实提供了一种灵活,直观的方法来访问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). (<200左右)。
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- C-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.