Lawes
Lawes

Reputation: 669

Is there function overloading in R?

It is possible to overload function in R?like the plot function,that means two functions have the same name but different parameter list,how to achieve?

Thanks!!!

Upvotes: 8

Views: 3810

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

What it sounds like you're looking for are methods. Many common functions (print, summary, plot) are overloaded in R with different methods being applied depending on the class of the object they are being applied to.

You mentioned plot, but I find it easier to start by looking at print. One common data structure that is used in R is an object of the class of data.frame. If you look at methods("print"), you will find a specific print method for an object with this class. This makes it print differently from a normal list although a data.frame, is a special type of list in R.

Example:

mydf <- data.frame(lengths = 1:3, values = 1:3, blah = 1:3)
mydf ### SAME AS print(mydf)
#   lengths values blah
# 1       1      1    1
# 2       2      2    2
# 3       3      3    3

print.default(mydf) ## Override automatically calling `print.data.frame`
# $lengths
# [1] 1 2 3
# 
# $values
# [1] 1 2 3
# 
# $blah
# [1] 1 2 3
# 
# attr(,"class")
# [1] "data.frame"

print(unclass(mydf))  ## Similar to the above
# $lengths
# [1] 1 2 3
# 
# $values
# [1] 1 2 3
# 
# $blah
# [1] 1 2 3
# 
# attr(,"row.names")
# [1] 1 2 3

You can also, of course, create your own methods. This might be useful when you want to print something with specialized formatting. Here's a simple example to print a vector with some unnecessary junk.

## Define the print method
print.SOexample1 <- function(x, ...) {
  cat("Your values:\n============", 
      format(x, width = 6), sep = "\n>>> : ")
  invisible(x)
}

## Assign the method to your object
## "print" as you normally would
A <- 1:5
class(A) <- "SOexample1"
print.SOexample1(A)
# Your values:
# ============
# >>> :      1
# >>> :      2
# >>> :      3
# >>> :      4
# >>> :      5

## Remove the "class" value to get back to where you started
print(unclass(A))
# [1] 1 2 3 4 5

As you can imagine, it is possible to have your methods do calculations in themselves. While that might seem convenient, that also ultimately leads to less "transparent" code.

Upvotes: 10

Related Questions