Skip to content

s3 methods on S4 objects

5 messages · Martin Morgan, steven mosher

#
On 01/12/2011 10:54 PM, steven mosher wrote:
Hi Steven --

This works for  me

setClass("A", representation=representation(df="data.frame"))

setMethod("as.data.frame", "A",
    function(x, row.names=NULL, optional=FALSE, ...)
{
    ## implementation, e.g.,
    callGeneric(x at df, row.names=row.names, optional=optional, ...)
})
Object of class "data.frame"
data frame with 0 columns and 0 rows
V1 V2 V3 V4 V5
1  0  0  0  0  0
2  0  0  0  0  0
3  0  0  0  0  0


Maybe you call setGeneric (no need to, setMethod will promote
as.data.frame automatically) in a way that does not specify the default
(arg useAsDefault) correctly?

Martin

  
    
#
On 01/13/2011 09:49 AM, steven mosher wrote:
callGeneric is not necessary, and I should just have said

  as.data.frame(x at df, row.names=row.names, optional=optional, ...)
I think of a generic 'foo' as a function, and inside that function are
functions foo,A-method, foo,B-method etc for classes A, B, .... When in
one of these methods, foo,A-method, the current generic is the function
'foo'. For as.data.frame, the generic is unambiguous ('as.data.frame' !)
and the interesting case are the group generics (?Logic, for instance),
where a single method

  setMethod("Logic", function(e1, e2) callGeneric(<YOUR CODE HERE>))

and you'll have in effect written 'methods' for all the operators
defined in the 'Logic' group. Cool.
The only code I had was what was written above -- setClass and
setMethod. I could also have

  setGeneric("as.data.frame")

and would have been ok -- the default behavior of setGeneric in this
case is to make a generic function as.data.frame, AND a method
as.data.frame,ANY-method. The as.data.frame,ANY-method is implemented as
base::as.data.frame, and is where objects not handled by methods I
implement might end up being dispatched to. In a new R session, try

  setGeneric("as.data.frame")
  showMethods(as.data.frame)
  selectMethod(as.data.frame, "ANY")

If I had done
function(x) standardGeneric("as.data.frame"))
Creating a generic for 'as.data.frame' in package '.GlobalEnv'
    (the supplied definition differs from and overrides the implicit generic
    in package 'base': Formal arguments differ: (x), (x, row.names,
optional, ...))
[1] "as.data.frame"

then I'm in trouble -- I've created a generic 'as.data.frame', but since
the signature of my generic differs from the signature of
base::as.data.frame, the default behavior does NOT create a
as.data.frame,ANY method.

Not sure if this helps or not...

Martin