If I a have a class called foo
, then it is straightforward to overload the summary
function
summary.foo = function(x, ...) print("bar")
However this technique does not work with the sd
function, that is
> bar = createFooClass()
> sd.foo = function(x, ...) print("Hi")
> sd(bar)
error: is.atomic(x) is not TRUE
What is the correct way of overloading this function?
You can hijack any non-generic function, make it (S3) generic and set the original version to be the default version. For example:
A final step, if this is in a package, is to add a
...
argument tosd.default
to allow passing of package checks:giving:
This then gives the desired behaviour:
This is documented in section 7.1 of the Writing R Extensions manual
You need to define a new generic for
sd
.The easiest way is to use S4, because it handles the default "sd" method automatically:
Look at the code of
sd()
---it effectively dispatches internally. In other words, it is not a generic function but a plain old regular function.The easiest may just be to modify
sd()
to branch on class foo.