### Name: Methods ### Title: General Information on Methods ### Aliases: Methods ### Keywords: programming classes methods ### ** Examples ## The rules for inheriting S3 methods. f3 <- function(x)UseMethod("f3") # an S3 generic to illustrate inheritance ## A class that extends a registered S3 class inherits that class' S3 ## methods. The S3 methods will be passed an object with the S3 class setClass("myFrame", contains = "data.frame", representation(date = "POSIXt", type = "character")) df1 <- data.frame(x = 1:10, y = rnorm(10), z = sample(letters,10)) mydf1 <- new("myFrame", df1, date = Sys.time()) ## "myFrame" objects inherit "data.frame" S3 methods; e.g., for `[` mydf1[1:2, ] # a data frame object (with extra attributes "date" and "type") ## Don't show: m1 <- mydf1[1:2,] attr(m1, "date") <- attr(m1, "type") <- NULL stopifnot(identical(m1, df1[1:2,])) ## End Don't show ## Extending an S3 class with inconsistent (instance-based) inheritance setClass("myDateTime", contains = "POSIXt") now <- Sys.time() # class(now) is c("POSIXt", "POSIXct") nowLt <- as.POSIXlt(now)# class(nowLt) is c("POSIXt", "POSIXlt") mCt <- new("myDateTime", now) mLt <- new("myDateTime", nowLt) ## S3 methods will be selected using instance-based information f3.POSIXct <- function(x) "The POSIXct result" f3.POSIXlt <- function(x) "The POSIXlt result" stopifnot(identical(f3(mCt), f3.POSIXct(mCt))) stopifnot(identical(f3(mLt), f3.POSIXlt(mLt))) ## An S4 class that does not contain a registered S3 class or object type ## selects S3 methods according to its S4 "inheritance" ## but only if the class definition requests this via S3methods=TRUE ## ( from version 2.9.1 on) setClass("classA", contains = "numeric", representation(realData = "numeric"), S3methods = TRUE) Math.classA <- function(x) {(getFunction(.Generic))(x@realData)} x <- new("classA", log(1:10), realData = 1:10) stopifnot(identical(abs(x), 1:10)) setClass("classB", contains = "classA") y <- new("classB", x) stopifnot(identical(abs(y), 1:10)) # (version 2.9.0 or earlier fails here) ## Note: with a class that tries to combine both S3 and S4 superclasses. ## The S3 inheritance is used and the S3 method for ## the S4 superclass will not be selected. setClass("classC", representation(x = "numeric")) # an S3 method for "[" (not a good idea, but it would work) `[.classc` <- function(x, ..., drop = TRUE) {x@x[...]} setClass("classD", contains = c("classC", "data.frame")) ## by the rule mentioned in the S3 method section, the ## S3 methods are selected from the S3 class defined; that is, "data.frame" ## If the user expected to inherit `[.classC`, no luck. xd <- new("classD", df1, x = 1:50) ## Note the error from `[.data.frame` try(xd[1:25]) ## Don't show: removeClass("classA"); removeClass("classB"); rm(x,y) removeClass("myDateTime") ## End Don't show