[R] oddity with method definition
Faheem Mitha
faheem at email.unc.edu
Tue Aug 28 16:42:01 CEST 2007
Hi Dr Lumley,
Thanks to you and Dr. Murdoch for your helpful explanations. See below.
On Mon, 27 Aug 2007, Thomas Lumley wrote:
> On Mon, 27 Aug 2007, Faheem Mitha wrote:
>> 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.
Actually, it does not appear to be wiped. getMethod finds the "baz"
version and the "foo" version, but it seems to use the default even for
foo, which is of course wrong. Am I missing something? See below. Thanks.
I do get this warning message. Don't know what it means, though.
Warning message:
in the method signature for function "bar" no definition for class:
âÂÂbazâ in: matchSignature(signature, fdef, where)
Faheem.
****************************************************************************
setClass("foo", representation(x="numeric"))
bar <- function(object)
{
return(0)
}
setGeneric("bar")
bar.foo <- function(object)
{
print(object at x)
}
setMethod("bar", "foo", bar.foo)
setMethod("bar", "baz", function(object) print("baz"))
bar <- function(object)
{
return(0)
}
bar.foo <- function(object)
{
print(object at x)
}
setMethod("bar", "foo", bar.foo)
f = new("foo", x= 1)
bar(f) # returns 0
*****************************************************************
> getMethod("bar", "baz")
Method Definition:
function (object)
print("baz")
Signatures:
object
target "baz"
defined "baz"
>
> getMethod("bar", "foo")
Method Definition:
function (object)
{
print(object at x)
}
Signatures:
object
target "foo"
defined "foo"
More information about the R-help
mailing list