Suppose I have an object x
from class foo
(representing some intervals):
x <- c("0;100", "0;20", "10;40", "10;40")
attr(x, "class") <- "foo"
table(x)
orders the elements of x
alphabetically:
0;100 0;20 10;40
1 1 2
but I as default, would prefer to order x
according to the length of the intervals. I expected that
table.foo <- function(x, ...) table(unclass(x), ...)[c(2, 3, 1)]
# or the sake of simplicity the way to find the ordering is not shown
leading to
table.foo(x)
0;20 10;40 0;100
1 2 1
would do the job. Unfortunately, as far as I see it, table
isn't a generic function (in contrast to e.g. plot
), so running table(x)
would not call table.foo(x)
. Is there a way to make table generic or more general: to make a function that will be called instead of table
? I tried setGeneric("table", table.foo)
but it seems not to be what I want: firstly, it produces infinite recursion, as table.foo
will be called in every case, even if the object passed to table
is not of class foo
and secondly, it seems to be a local effect (on the computer running the code) for table
, but not a general effect for table.foo
, which shall be distributed by a package.