I've created a custom S4 class, and the idea is that it represents a vector that's always sorted, so I don't want sort()
to actually do anything to it. So I defined a stub version of sort()
for my class:
MyClass <- methods::setClass("MyClass", slots=list(x="numeric"))
setMethod("sort", signature(x="MyClass"), function(x, ...){}) # Do nothing
Then, I want to calculate a quantile of my class. R's quantile()
function internally calls sort()
. However, the sort()
used inside quantile()
is not aware of my S4 method, because it dispatches using UseMethod()
(the S3 dispatcher) and not standardGeneric()
, the S4 dispatcher. This is demonstrated below:
options(error=traceback)
instance = MyClass()
quantile(instance, 0.5)
This returns a call stack like this:
5: order(x, na.last = na.last, decreasing = decreasing)
4: sort.default(x, partial = unique(c(lo, hi)))
3: sort(x, partial = unique(c(lo, hi)))
2: quantile.default(instance, 0.5)
1: quantile(instance, 0.5)
Since sort.default
is being called, it is evident that my custom sort
implementation isn't being used.
Is there a simple way to get R to use my S4 method here? I realise I can also define sort.MyClass
(the S3 way), but if I do this, what is the point of having an S4 method at all? It seems like S4 is incompatible with core R methods which renders it fairly useless.