Generics and Methods

Object-Oriented Programming with S3 and R6 in R

Richie Cotton

Data Evangelist at DataCamp

summary(c(TRUE, FALSE, NA, TRUE))
   Mode   FALSE    TRUE    NA's 
logical       1       2       1
summary(rgamma(1000, 1))
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
0.000354 0.276500 0.690300 1.020000 1.384000 9.664000
Object-Oriented Programming with S3 and R6 in R

 

 

 

function overloading = input-dependent

                                                function behavior

Object-Oriented Programming with S3 and R6 in R

ch2_1-generics-and-methods.007.png

Object-Oriented Programming with S3 and R6 in R

ch2_1-generics-and-methods.008.png

Object-Oriented Programming with S3 and R6 in R

ch2_1-generics-and-methods.009.png

Object-Oriented Programming with S3 and R6 in R

ch2_1-generics-and-methods.010.png

Object-Oriented Programming with S3 and R6 in R
print
function (x, ...) 
UseMethod("print")
<bytecode: 0x1062f0870>
<environment: namespace:base>
Object-Oriented Programming with S3 and R6 in R

Methods are named generic.class

  • print.Date
  • summary.factor
  • unique.array
Object-Oriented Programming with S3 and R6 in R

Method signatures contain generic signatures

args(print)
function (x, ...) 
NULL
args(print.Date)
function (x, max = NULL, ...) 
NULL
Object-Oriented Programming with S3 and R6 in R

 

 

 

pass arguments between methods with ...

include it in both generic and methods

Object-Oriented Programming with S3 and R6 in R
print.function
function (x, useSource = TRUE, ...) 
.Internal(print.function(x, useSource, ...))
Object-Oriented Programming with S3 and R6 in R
print.Date
function (x, max = NULL, ...) 
{
    if (is.null(max)) 
        max <- getOption("max.print", 9999L)
    if (max < length(x)) {
        print(format(x[seq_len(max)]), max = max, ...)
        cat(" [ reached getOption(\"max.print\") -- omitted", 
            length(x) - max, "entries ]\n")
    }
    else print(format(x), max = max, ...)
    invisible(x)
}
Object-Oriented Programming with S3 and R6 in R

 

 

ch2_1-generics-and-methods.030.png

Object-Oriented Programming with S3 and R6 in R

ch2_1-generics-and-methods.031.png

Object-Oriented Programming with S3 and R6 in R

ch2_1-generics-and-methods.032.png

Object-Oriented Programming with S3 and R6 in R

Summary

  • Functions split into generic + method
  • Methods named generic.class
  • Method args contain generic args
  • Include a ... arg
  • Use lower_snake_case or lowerCamelCase
Object-Oriented Programming with S3 and R6 in R

Let's practice!

Object-Oriented Programming with S3 and R6 in R

Preparing Video For Download...