[Rd] S4 and head() problems

Martin Maechler maechler at stat.math.ethz.ch
Thu Dec 3 15:06:42 CET 2009


Hi Robin,

>>>>> "Robin" == Robin Hankin <rksh1 at cam.ac.uk>
>>>>>     on Thu, 03 Dec 2009 11:04:03 +0000 writes:

    > Hi
    > I am having difficulty defining an S4 method for head() and tail().

    > I can't quite provide minimal self-contained code
    > because the problem appears to require the whole corpus
    > of my package; and there also appears to be a difference
    > between sourcing the lines directly, and having them
    > installed in a package.

    > The lines in question (I think) are:

    > setClass("mdm",
    > representation = representation(
    > xold  = "matrix",
    > types = "factor"
    > )
    > )

    > "mdm" <- function(xold, types){
    > new("mdm", xold=xold, types=types)
    > }

    > setGeneric("head",function(x,...){standardGeneric("head")})

I would not use setGeneric() here
rather only setMethod() :

    > setMethod("head",signature="mdm",function(x,n=6,...){
    > mdm(head(x at xold,n=n,...) , types=factor(head(x at types,n=n,...)))
    > } )


    > If the above lines are part of the package source, and I install the package
    > then sometimes  I get errors like

    >> head(toy_mm())
    > Error in function (classes, fdef, mtable)  :
    > unable to find an inherited method for function "head", for signature 
    > "matrix"
    >> 

    > and sometimes it works as desired.

    > Why should head() not be able to take the first few lines of a matrix?
    > It seems to be "forgetting" that head.matrix() exists.

    > Can anyone give me some pointers for debugging this problem?

    > rksh

you did not mention if your package uses a NAMESPACE
and if yes, what exactly you import and export,
and that can matter quite a bit.

In the Matrix package, we do *not* call setGeneric() for head,
just setMethod(), and I'd advise you to do that too.

Why you get different behavior depending on how exactly you load
the code seems very had to diagnose from a distance.

Regards,
Martin



More information about the R-devel mailing list