Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Function overloading

Does R support function overloading ??

I want to do something in the lines of :

g <- function(X,Y) { # do something and return something } 
g <- function(X) { # do something and return something} 
like image 243
MadSeb Avatar asked Feb 13 '12 18:02

MadSeb


2 Answers

EDIT, following clarification of the question in comments above:

From a quick glance at this page, it looks like Erlang allows you to define functions that will dispatch completely different methods depending on the arity of their argument list (up to a ..., following which the arguments are optional/don't affect the dispatched method).

To do something like that in R, you'll probably want to use S4 classes and methods. In the S3 system, the method that is dispatched depends solely on the class of the first argument. In the S4 system, the method that's called can depend on the classes of an arbitrary number of arguments.

For one example of what's possible, try running the following. It requires you to have installed both the raster package and the sp package. Between them, they provide a large number of functions for plotting both raster and vector spatial data, and both of them use the S4 system to perform method dispatch. Each of the lines returned by the call to showMethods() corresponds to a separate function, which will be dispatched when plot() is passed x and y arguments that having the indicated classes (which can include being entirely "missing").

> library(raster)
> showMethods("plot")
Function: plot (package graphics)
x="ANY", y="ANY"
x="Extent", y="ANY"
x="Raster", y="Raster"
x="RasterLayer", y="missing"
x="RasterStackBrick", y="ANY"
x="Spatial", y="missing"
x="SpatialGrid", y="missing"
x="SpatialLines", y="missing"
x="SpatialPoints", y="missing"
x="SpatialPolygons", y="missing"

R sure does. Try, for an example:

plot(x = 1:10)
plot(x = 1:10, y = 10:1)

And then go have a look at how the function accomplishes that, by typing plot.default.

In general, the best way to learn how implement this kind of thing yourself will be to spend some time poking around in the code used to define functions whose behavior is already familiar to you.

Then, if you want to explore more sophisticated forms of method dispatch, you'll want to look into both the S3 and S4 class systems provided by R.

like image 130
Josh O'Brien Avatar answered Sep 23 '22 10:09

Josh O'Brien


This is usually best done through optional arguments. For example:

g <- function(X, Y=FALSE) {
    if (Y == FALSE) {
        # do something
    }
    else {
        # do something else
    }
}
like image 36
David Robinson Avatar answered Sep 20 '22 10:09

David Robinson