From Matthias.Kohl at uni-bayreuth.de  Fri Feb 11 10:40:44 2005
From: Matthias.Kohl at uni-bayreuth.de (Matthias Kohl)
Date: Fri Feb 11 09:38:39 2005
Subject: [Rd] Canonical S4 Method signature
In-Reply-To: <Pine.OSF.4.58.0502101640490.131187@odin.mdacc.tmc.edu>
References: <Pine.OSF.4.58.0502101640490.131187@odin.mdacc.tmc.edu>
Message-ID: <420C7D9C.4090001@uni-bayreuth.de>

Paul Roebuck schrieb:

>I have trouble finding applicable examples of S4 methods.
>Could someone tell me the canonical method for a function
>that takes either one or two arguments corresponding to
>dimensions? So if vector output desired, only one argument
>'n' would be provided. For matrix, two would be provided
>corresponding to 'm' and 'n' in that order. And therein
>lies the rub as I don't really want to require specifying
>the argument name in order to do this.
>
>foo(3)		# n = 3
>foo(3, 4)	# m = 3, n = 4
>foo(n = 3, 4)	# m = 4, n = 3
>
>What I have come up with thus far is below but that reverses
>the order for second case. I could swap them internally if
>I knew whether they were specified by name.
>
>setGeneric("foo", function(n, m = n) {
>    cat("generic", match.call()[[1]], "\n")
>    standardGeneric("foo")
>})
>
>One other alternative might be to just use dots for the
>function argument and assign them names internally.
>
>Similar functions in some package? Suggestions (besides
>not using S4)?
>
>TIA
>
>----------------------------------------------------------
>SIGSIG -- signature too long (core dumped)
>
>______________________________________________
>R-devel@stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-devel
>
>  
>
Hi,

maybe the following is a starting point and comes close to what you want ...

Matthias


if(!isGeneric("foo"))
    setGeneric("foo", function(m, n) standardGeneric("foo"))

setMethod("foo", signature(m = "missing", n = "numeric"),
    function(n){ 
        # do something
        # for example
        print(n)
    })

setMethod("foo", signature(m = "numeric", n = "numeric"),
    function(m, n){ 
        # do something
        # for example
        print(m)
        print(n)
    })

foo(3, 4)
foo(n = 3, 4)
# unfortunatelly you have to do
foo(,3)
# or
foo(n = 3)


[Rd] Canonical S4 Method signature
Matthias Kohl