[Rd] Overloading methods in R
Tony Plate
tplate at acm.org
Wed Apr 20 17:27:33 CEST 2005
If I understand what you are looking for, I believe your assumption (1)
is FALSE, not TRUE as you suspected.
One thing to realize is that "methods" in R are very different to those
in other common "object-oriented" languages such as C++, Java, or
Python. One difference is that methods are not intimately associated
with a class definition -- the method dispatch system pulls disparate
pieces of information together. Another difference is that the choice
of which method to invoke can depend on all arguments, not just the first.
Yet another thing to realize is that R has two class systems (commonly
known as something like "S3" and "S4" methods and classes). Each has
its own way of defining classes, generic functions and methods. The S4
class system offers more control over which method is called. Consult
the "Green Book" for details of the S4 system. (See the FAQ for full
details of the "Green Book").
Here's an example of something like what you are asking for, using the
S4 class system. Note that this example doesn't involve the definition
of any classes, just a generic and methods for some standard classes.
Also note that a generic and its methods should have the same argument
names.
> setGeneric("foo", function(x,y) standardGeneric("foo"))
[1] "foo"
> setMethod("foo", c("ANY", "missing"),
+ function(x,y) "x:any y:missing")
[1] "foo"
> setMethod("foo", c("numeric", "numeric"),
+ function(x,y) "x:numeric y:numeric")
[1] "foo"
> setMethod("foo", c("missing", "numeric"),
+ function(x,y) "x:missing y:numeric")
[1] "foo"
> foo(1,2)
[1] "x:numeric y:numeric"
> foo(1)
[1] "x:any y:missing"
> foo(y=2)
[1] "x:missing y:numeric"
> foo(y="bar")
Error in foo(y = "bar") : no direct or inherited method for function
'foo' for this call
>
(You can execute the above commands under Windows by copying the entire
transcript to the clipboard, and then using the "Paste commands only"
menu item under the "Edit" menu in the "R console" window.)
hope this helps to at least get you started,
Tony Plate
Ali - wrote:
> (1) It seems to me that, generally, in R it is not possible to overload
> functions. Is that right?
>
> (2) Assuming that the above is true, or partially true, is there any
> extra packages to handle overloading in R?
>
> (3) Assuming (1) is TRUE and (2) is FALSE, can anyone provide some
> advice on developing some function that understand what the arguments
> are and then calls the right overloaded function?
>
> It would be something like this:
>
> overloadedFunction1 <- function(x) {};
>
> overloadedFunction2 <- function(x, y) {};
>
> theFunction <- function(...)
> {
> # How to identify ... and call the right overloaded function?
> }
>
> ______________________________________________
> R-devel at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
More information about the R-devel
mailing list