In R inheritance can be implemented by extending a list based class the following way:
Assume lmo
is a object of class lm
obtained from linear model fitting. The class could simply be extended by:
x <- rnorm(1000)
y <- rexp(1000)
lmo <- lm(x~y)
lmo$addition <- "some more information"
class(lmo) <- c("lmext","lm")
I could still use all methods like summary.lm
that worked for lm
but also defined custom methods. Obviously there are lots of situations in which you want to just have minimal additions and still want to be able to use all the methods from the parent class.
What is the best way to add additional properties and implement method inheritance for classes that are not based on lists like e.g. time series? Here's what I could imagine:
ts1 <- ts(rnorm(100),start = c(1990,1),frequency = 4)
attr(ts1,"additional") <- "some more information"
class(ts1) <- c("tsext","ts")
print.tsext <-
# some method that uses the original print method for ts, plus extracts
# the additional information
Is this a good way of achieving that operators like +
etc. still work without redefining everything for the new class? Is there something better? And is there a way of keeping the additional class / attributes when for example adding two series to each other without redefining all the basic operators?