R:什么是老虎机?

时间:2011-01-17 13:58:51

标签: oop r s4 slot r-faq

有谁知道R中的插槽是什么?

我没有找到其含义的解释。我得到一个递归定义: “插槽函数返回或设置有关对象的各个插槽的信息”

帮助将不胜感激, 谢谢 - 胡同

4 个答案:

答案 0 :(得分:73)

插槽与S4对象相关联。槽可以被视为对象的一部分,元素或“属性”。假设你有一个汽车对象,那么你可以拥有“价格”,“门数”,“发动机类型”,“里程”的插槽。

在内部,它代表一个列表。一个例子:

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

这里,价格,numberDoors,typeEngine和里程数是S4类“Car”的插槽。这是一个简单的例子,实际上插槽本身可以是复杂的对象。

可以通过多种方式访问​​插槽:

> aCar@price
[1] 20000
> slot(aCar,"typeEngine")
[1] "V6"    

或通过构建特定方法(参见额外文档)。

有关S4编程的更多信息,请参阅this question。如果这个概念对你来说仍然含糊不清,那么面向对象编程的一般性介绍可能有所帮助。

PS:注意与数据框和列表的区别,您可以使用$来访问命名变量/元素。

答案 1 :(得分:16)

正如names(variable)列出复杂变量的所有$ - 可访问名称一样,

slotNames(object)列出了对象的所有插槽。

非常方便地发现您的健康物品包含哪些物品以供您观赏。

答案 2 :(得分:10)

除了@Joris指出的资源,加上他自己的答案,请尝试阅读?Classes,其中包括以下插槽:

 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.
      ....

答案 3 :(得分:-1)

不知道为什么R必须重新定义所有内容。大多数普通的编程语言将它们称为“属性”或“属性”。

相关问题