[R] oddity with method definition
Thomas Lumley
tlumley at u.washington.edu
Tue Aug 28 00:32:33 CEST 2007
On Mon, 27 Aug 2007, 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)
>
> bar(f)
>
> # bar(f) gives 1.
Not for me. It gives
> bar(f)
Error: object "f" not found
Error in bar(f) : error in evaluating the argument 'object' in selecting a
method for function 'bar'
However, if I do
f = new("foo", x= 1)
first, it gives 1.
> bar <- function(object)
> {
> return(0)
> }
Here you have masked the generic bar() with a new function bar(). Redefining bar() is the problem, not the second setMethod().
> bar.foo <- function(object)
> {
> print(object at x)
> }
> setMethod("bar", "foo", bar.foo)
Because there was a generic bar(), even though it is overwritten by the new bar(), setMethod() doesn't automatically create another generic.
> f = new("foo", x= 1)
>
> bar(f)
>
> # bar(f) gives 0, not 1.
>
Because bar() isn't a generic function
> bar
function(object)
{
return(0)
}
If you had used setGeneric() before setMethod(), as recommended, your example would have done what you expected, but it would still have wiped out any previous methods for bar() -- eg, try
setMethod("bar","baz", function(object) print("baz"))
before you redefine bar(), and notice that getMethod("bar","baz") no longer finds it.
-thomas
Thomas Lumley Assoc. Professor, Biostatistics
tlumley at u.washington.edu University of Washington, Seattle
More information about the R-help
mailing list