有人知道R中的slot是什么吗?
我没有找到它的解释。我得到了一个递归的定义: “Slot函数返回或设置对象的单个槽的信息”
希望能得到帮助, 谢谢 - 艾利
Slots与S4对象相关联。Slot可以被看作是对象的一部分、元素或者“属性”。假设你有一个汽车对象,那么你可以拥有slots“价格”、“车门数量”、“发动机类型”、“里程数”。
在内部,它被表示成一个列表。例如:
setClass("Car",representation=representation(
price = "numeric",
numberDoors="numeric",
typeEngine="character",
mileage="numeric"
))
aCar <- new("Car",price=20000,numberDoors=4,typeEngine="V6",mileage=143)
> aCar
An object of class "Car"
Slot "price":
[1] 20000
Slot "numberDoors":
[1] 4
Slot "typeEngine":
[1] "V6"
Slot "mileage":
[1] 143
在这里,price、numberDoors、typeEngine和mileage是S4类“Car”的插槽。这只是一个简单的示例,在实际中,插槽本身可以再次是复杂对象。
插槽可以通过多种方式访问:
> aCar@price
[1] 20000
> slot(aCar,"typeEngine")
[1] "V6"
或通过构建特定方法来实现(请参见额外文档)。
有关S4编程的更多信息,请参阅此问题。 如果这个概念仍然对您来说很模糊,那么面向对象编程的一般介绍可能会有所帮助。
附:请注意与数据框架和列表的区别,其中使用$
访问命名变量/元素。
slot(aCar, "price")
的示例,作为另一种用法,特别是因为问题提出者正在查看 slot()
函数。 - Gavin SimpsongetSlots()
,或者使用 slotNames()
获取它们的名称。 - Laurent$
和[[]]
等价的符号?因此,可以使用element(aCar, "typeEngine")
代替aCar$typeEngine
吗? - Samuel Saari就像names(variable)
列出复杂变量中所有可访问的$
名称一样,slotNames(object)
也会列出对象的所有插槽。
非常方便,可以发现您拟合对象包含的好东西供您观看。
除了@Joris指向的资源和他自己的答案之外,尝试阅读?Classes
,其中包括有关slots的以下内容:
Slots:
The data contained in an object from an S4 class is defined
by the _slots_ in the class definition.
Each slot in an object is a component of the object; like
components (that is, elements) of a list, these may be
extracted and set, using the function ‘slot()’ or more often
the operator ‘"@"’. However, they differ from list
components in important ways. First, slots can only be
referred to by name, not by position, and there is no partial
matching of names as with list elements.
....
不知道为什么R语言要重新定义所有东西。大多数普通编程语言称它们为“属性”或“特性”。
slot()
函数的帮助文档 - 它并不旨在记录什么是槽,而只是如何访问它们。 - Gavin Simpson