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}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
rasterpackage and thesppackage. 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 toshowMethods()corresponds to a separate function, which will be dispatched whenplot()is passedxandyarguments that having the indicated classes (which can include being entirely"missing").R sure does. Try, for an example:
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.