我正在创建两个S4类,其中类Employee继承自另一个Person类。
这两个类的定义如下:
setClass("Person", slots = list(name="character", age="numeric"))
setClass("Employee", slots = list(boss="Person"))
我正在为这两个类创建一个实例
alice <- new("Person", name="Alice", age = 40)
这很有效,但是当我尝试使用:
创建Employee实例时john <- new("Employee", name = "John", age = 20, boss= alice)
它给出如下错误:
Error in initialize(value, ...) :
invalid names for slots of class “Employee”: name, age
我不能以这种方式创建对象吗?
答案 0 :(得分:2)
Per nrussel的评论:
函数contains
的参数setClass
处理继承。您希望类Employee
从类Person
继承(即员工是一种特殊类型的人)。所以
setClass("Person", slots = list(name="character", age="numeric"))
setClass("Employee", slots = list(boss="Person"), contains = "Person")
会做到这一点。
> alice <- new("Person", name="Alice", age = 40)
> john <- new("Employee", name = "John", age = 20, boss= alice)
> john
An object of class "Employee"
Slot "boss":
An object of class "Person"
Slot "name":
[1] "Alice"
Slot "age":
[1] 40
Slot "name":
[1] "John"
Slot "age":
[1] 20