This page collects some S4 examples. More details about this topic can be found on Hadley's Wiki pages including S3, S4, and R5 systems.
Examples:
- S4 Class and Method
This is a quick example to use S4 class and method to extend functions where all
foo.*
need to have the same number of arguments. S4 signature will determine the input type and call the corresponding function.rm(list = ls(all.names = TRUE)) foo.default <- function(x, y, z) cat("call foo.default\n") foo.double <- function(x, y, z) cat("call foo.double\n") foo.myobj <- function(x, y = NULL, z = NULL) cat("call foo.myobj\n") setClass("myobj", representation(x = "numeric")) setGeneric(name = "foo", useAsDefault = foo.default) setMethod(f = "foo", signature = signature(x = "myobj"), definition = foo.myobj) setMethod(f = "foo", signature = signature(x = "numeric", y = "numeric", z = "numeric"), definition = foo.double) a <- new("myobj") foo(a) foo(1) foo(1, 2, 3)
- More S4 Methods
This is a silly example, but somehow useful in some cases with different number and different type of input arguments.
rm(list = ls(all.names = TRUE)) foo.default <- function(x, dim, bldim, ctxt){ if(!missing(ctxt)){ stop("Input is incorrect.") } else{ foo.2(NULL, x, dim, bldim) } cat("cat foo.default\n") } foo.1 <- function(x, dim = NULL, bldim = NULL, ctxt = NULL){ cat("call foo.1\n") } foo.2 <- function(x = NULL, dim, bldim, ctxt){ cat("call foo.2\n") } foo.3 <- function(x, dim = NULL, bldim = NULL, ctxt = NULL){ cat("call foo.3\n") } setClass("myobj", representation(x = "numeric")) setGeneric(name = "ownany", useAsDefault = foo.default) setMethod(f = "ownany", signature = signature(x = "myobj"), definition = foo.1) setMethod(f = "ownany", signature = signature(dim = "numeric", bldim = "numeric", ctxt = "numeric"), definition = foo.2) setMethod(f = "ownany", signature = signature(x = "numeric", dim = "missing", bldim = "missing", ctxt = "missing"), definition = foo.3) a <- new("myobj") ownany(a) ownany(dim = 1, bldim = 2, ctxt = 3) ownany(1) ownany(1, 2, 3)