S3 Classes
Purpose
To code S3 Classes for various distributions
> Univariate <- function(x) { + object <- list(name = x) + class(object) <- x + return(object) + } > printDist <- function(x) { + if (is.null(attr(x, "class"))) { + print("BOSS, INPUT THE DISTRIBUTION") + } + else UseMethod("printDist", x) + } > printDist.Discrete <- function(x) { + print("In Discrete") + NextMethod() + } > printDist.Poisson <- function(x) { + print("POISSON DISTRIBUTION") + } > x <- Univariate(c("Discrete", "Poisson")) > printDist(x) [1] "In Discrete" [1] "POISSON DISTRIBUTION" > x <- Univariate(c("Continous", "Poisson")) > printDist(x) [1] "POISSON DISTRIBUTION" > x <- Univariate(c("Continous", "Poisson")) > printDist(x) [1] "POISSON DISTRIBUTION" |
Extending Internal Generics
> myclass <- function(x, n) { + structure(x, class = "myclass", n = n) + } > c.myclass <- function(..., recursive = FALSE) { + dots <- list(...) + ns <- sapply(dots, attr, which = "n") + classes <- rep("myclass", length(dots)) + res <- structure(unlist(dots, recursive = FALSE), class = classes) + attr(res, "n") <- ns + return(res) + } > `[.myclass` <- function(x, i) { + y <- unclass(x)[i] + ns <- attr(x, "n")[i] + class(y) <- "myclass" + attr(y, "n") <- ns + return(y) + } > x1 <- myclass(1, 5) > x2 <- myclass(2, 6) > print(c(x1, x2)[2]) [1] 2 attr(,"class") [1] "myclass" attr(,"n") [1] 6 > z <- c(x1, x2) > print(attr(z, "class")) [1] "myclass" "myclass" > print(attr(z, "n")) [1] 5 6 |
Generalizing Constructor functions
> geom <- function(x, ...) UseMethod("geom") > geom.default <- function(x, ...) { + object <- list(area = x^2) + class(object) <- "geom" + return(object) + } > geom.rectangle <- function(x, ...) { + args <- list(...) + object <- list(area = x * as.numeric(args[1])) + class(object) <- "geom" + return(object) + } > geom.triangle <- function(x, ...) { + args <- list(...) + object <- list(area = (x * as.numeric(args[1]) * as.numeric(args[2]))/2) + class(object) <- "geom" + return(object) + } > my.object1 <- geom(3) > print(my.object1) $area [1] 9 attr(,"class") [1] "geom" > print(attr(my.object1, "class")) [1] "geom" > my.object2 <- geom.rectangle(3, 4) > print(my.object2) $area [1] 12 attr(,"class") [1] "geom" > print(attr(my.object2, "class")) [1] "geom" > my.object3 <- geom.triangle(3, 4, 5) > print(my.object3) $area [1] 30 attr(,"class") [1] "geom" > print(attr(my.object3, "class")) [1] "geom" |
Discrete Binomial Hyper Dirac Nbinom Geom Pois Continous Beta Logis Cauchy Lnorm Chisq Norm Exp T F Unif Gamma Weibull