[R] How to write an S4 method for sum or a Summary generic

Swinton, Jonathan Jonathan.Swinton at astrazeneca.com
Mon Apr 19 14:16:09 CEST 2004


If I have a class Foo, then i can write an S3 method for sum for it:

>setClass("Foo",representation(a="integer"));aFoo=new("Foo",a=c(1:3,NA))
>sum.Foo <- function(x,na.rm){print(x);print(na.rm);sum(x at a,na.rm=na.rm)}
>sum(aFoo)

But how do I write an S4 method for this? All my attempts to do so have
foundered. For example
>setMethod("sum",signature("Foo","logical"),
function(x,na.rm){print(x);print(na.rm);sum(x at a,na.rm=na.rm)}
creates a method which seems to despatch on na.rm="Foo":
> getMethods("sum")
na.rm = "ANY":
function (..., na.rm = FALSE) 
.Internal(sum(..., na.rm = na.rm))

na.rm = "Foo":
function (..., na.rm = FALSE) 
{
    .local <- function (x, na.rm) 
    {
        print(x)
        print(na.rm)
        sum(x at a, na.rm = na.rm)
    }
    .local(..., na.rm = na.rm)
}

na.rm = "missing":
function (..., na.rm = FALSE) 
.Internal(sum(..., na.rm = na.rm))
##:    (inherited from na.rm = "ANY")

Pages 350-352 of the Green book discuss at some length how to write a
generic function for Summary group generics which uses tail recursion to
allow the correct method to be called on each member of a ... argument list.
But it gives no examples of what individual method functions need to look
like. Any ideas or a place to look for working code?

Jonathan Swinton, Statistical Scientist, Computational Biology, Pathway
Analysis, Global Sciences and Information, AstraZeneca.




More information about the R-help mailing list