Reputation: 2715
I am having trouble defining a class that inherits all of a data.frame's methods. For example, if I was to define a class timeline this could be represented as a data.frame:
data.frame(task = c("Read Permutation City", "Learn S4 oop"),
from = c(Sys.Date(), Sys.Date()),
to = c(Sys.Date() + 5, Sys.Date() + 1))
Instead I would like to define a class "timeline" that would retain all of a data.frames methods but override and add several methods (e.g. plot, summary and window). In other languages this is fairly straightforward.
I would like to do this using an S4 class structure. I tried to implement an S4 class using the contains
argument, however, I must be doing something wrong as the results are not what you expect from a data.frame.
timeline <- setClass(Class = "timeline", contains = "data.frame")
timeline <- function(task, from, to) {
new("timeline", data.frame(task = task, from = from, to = to))
}
tm <- timeline("Run", Sys.Date(), Sys.Date() + 5)
getClass("timeline") # Class "timeline" .... Extends: Class "data.frame", directly
inherits(tm, "data.frame") # TRUE
nrow(tm) # 0
ncol(tm) # 3
tm # Prints S4 info
print(tm) # Expected output
What is the right way of doing this?
Upvotes: 5
Views: 631