[R] oddity with method definition

Duncan Murdoch murdoch at stats.uwo.ca
Tue Aug 28 00:19:56 CEST 2007


On 27/08/2007 5:47 PM, Faheem Mitha wrote:
> Just wondered about this curious behaviour. I'm trying to learn about 
> classes. Basically setMethod works the first time, but does not seem to 
> work the second time.
>                                                                  Faheem.
> *************************************************************************
> setClass("foo", representation(x="numeric"))
> 
> bar <- function(object)
>    {
>      return(0)
>    }
> 
> bar.foo <- function(object)
>    {
>      print(object at x)
>    }
> setMethod("bar", "foo", bar.foo)

This changes the definition of bar:  now it becomes a generic function 
instead of a simple function.

> 
> bar(f)
> 
> # bar(f) gives 1.

(You forgot the f = new("foo", x= 1) line, but that's somewhat obvious.)
> 
> bar <- function(object)
>    {
>      return(0)
>    }

Now bar is a regular function again.
> 
> bar.foo <- function(object)
>    {
>      print(object at x)
>    }
> setMethod("bar", "foo", bar.foo)

Now the generic would call that method, but you've wiped out the generic.

> 
> f = new("foo", x= 1)
> 
> bar(f)
> 
> # bar(f) gives 0, not 1.

The problem is that setting a method on a regular function automagically 
creates a generic for it, but redefining a function doesn't remove the 
generic.  It's still there, somewhere in R's insides, and if you could 
find it to call it your method would get called.  But you're calling the 
plain old bar() instead.

This behaviour makes more sense if you think about generics in other 
packages.  There's a generic called "show" in the methods package.  But 
you can define your own function called "show", and in your workspace, 
you'd want to call that, not the one from methods.

I'd recommend using setGeneric() to create a generic, rather than 
depending on the automatic creation, to avoid this kind of confusion.

Duncan Murdoch



More information about the R-help mailing list