I am creating two S4 classes, where class Employee inherits from the other class Person.
The definition for both the classes is as follows:
setClass("Person", slots = list(name="character", age="numeric"))
setClass("Employee", slots = list(boss="Person"))
I am creating once instance each of these two classes,
alice <- new("Person", name="Alice", age = 40)
This works well, but when I try to create an instance of Employee using :
john <- new("Employee", name = "John", age = 20, boss= alice)
It gives the error as below :
Error in initialize(value, ...) :
invalid names for slots of class “Employee”: name, age
Can I not create the object in this fashion ?
Per nrussel's comment:
the argument contains of the function setClass deals with inheritance. You want the class Employee to inherit from the class Person (i.e. an employee is a special type of person). So
setClass("Person", slots = list(name="character", age="numeric"))
setClass("Employee", slots = list(boss="Person"), contains = "Person")
will do the trick.
> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With