Example: I have a MatrixPair
class and a NamedMatrixPair
(inherits from MatrixPair
). MatrixPair$show()
prints the two matrices in it, and I want NamedMatrixPair$show()
to print some extra info but then also append whatever MatrixPair$show()
would print.
Obviously this is a toy example; I know you can name columns in matrices etc., but that's not the point of my question.
I'm super-new to R. I'm using reference classes for this.
This is a super-common thing in most languages I know (e.g., super.show()
or base.show()
or whatever). I don't know if that's even possible in R though.
MatrixPair <- setRefClass(
'MatrixPair',
fields = list(
m1 = 'matrix',
m2 = 'matrix'),
methods = list(
initialize = function(...) {
callSuper(...)
},
showX = function() {
cat(sprintf("2 matrices, with dimensions %s x %s:\n", nrow(m1), ncol(m1)))
methods::show(m1)
methods::show(m2)
},
)
)
NamedMatrixPair <- setRefClass(
'NamedMatrixPair',
contains = 'MatrixPair',
fields = list(
'rowName' = 'character',
'colName' = 'character'
),
methods = list(
initialize = function(m1, m2, ...) {
callSuper(m1 = m1, m2 = m2, ...)
},
show = function() {
cat(sprintf("rows: %s ; cols: %s", rowName, colName))
# I want to call show() for parent class MatrixPair.
# methods::show(.self) won't do it
# show(as(MatrixPair, .self)) - i.e. casting the derived class object to the parent class - won't do it
}
)
)
EDIT: I figured out the solution.
show = function() {
cat(sprintf("rows: %s ; cols: %s", rowName, colName))
callSuper()
}