Is there an overload of functions in R?

Can I overload a function in R? as a plot function, which means that two functions have the same name but a different list of parameters, how to achieve?

Thanks!!!

+8
r
source share
1 answer

It looks like you are looking for methods . Many common functions ( print , summary , plot ) are overloaded in R using different methods depending on the class object to which they are applied.

You mentioned plot , but it's easier for me to start by looking at print . One common data structure that is used in R is a 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 different from a regular 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 create your own methods . This can be useful if you want to print something with special formatting. Here is a simple example for printing a vector with some unnecessary junk file.

 ## 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, you can do the calculation methods yourself. Although this may seem convenient, it also ultimately leads to less "transparent" code.

+8
source share

All Articles