[R] Problem with generic methods

Martin Morgan mtmorgan at fhcrc.org
Sat Jun 6 00:14:42 CEST 2009


Rainer M Krug <r.m.krug at gmail.com> writes:

> Hi
>
> I want to create a new generic method, but I end up with an error
> (evaluation nested too deeply). see the transcript below.
> The function beginYear.Fun() works, but not beginYear.
>
> I have no idea why.
>
> Any ideas welcome,
>
> Rainer
>
>
>> setClass("fun", representation(x = "numeric"))
> [1] "fun"
>> new("fun")
> An object of class “fun”
> Slot "x":
> numeric(0)
>
>> setGeneric(
>            "beginYear",
>            function(object, ...) standardGeneric("beginYear")
> )
> setGeneric(
> +            "beginYear",
> +            function(object, ...) standardGeneric("beginYear")
> + )
> [1] "beginYear"
>
>> beginYear.Fun = function(x) x^2
>> beginYear.Fun(4)
> [1] 16

Are you confusing S3 and S4 method systems? The .Fun has no special
meaning in S4

>> setMethod(
>           "beginYear",
>           signature( object = "numeric" ),
>           beginYear
>           )

here the beginYear,numeric-method is defined to invoke the beginYear
generic, so you end up calling yourself. You might have meant

  setMethod(beginYear, signature(object="numeric"), beginYear.Fun)

but I would have written

  setMethod(beginYear, signature(object="numeric"),
            function(object, ...) object^2)

Martin

> setMethod(
> +           "beginYear",
> +           signature( object = "numeric" ),
> +           beginYear
> +           )
> [1] "beginYear"
>
>> beginYear.Fun(4)
> [1] 16
>
>> beginYear(4)
> Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
>>

-- 
Martin Morgan
Computational Biology / Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N.
PO Box 19024 Seattle, WA 98109

Location: Arnold Building M1 B861
Phone: (206) 667-2793




More information about the R-help mailing list