Deliberate Practice R
Purpose
To code classes and explore further concepts
Classes with out explicit slots
> setClass("seq", contains = "numeric", prototype = prototype(numeric(3))) [1] "seq" > s1 <- new("seq") > s1 An object of class "seq" [1] 10.0000000 4.9208030 0.5407331 > slotNames(s1) [1] ".Data" |
initializeMethod
> setMethod("initialize", "seq", function(.Object) { + .Object[1] <- 10 + .Object[2] <- rnorm(1, 0, 10) + .Object[3] <- runif(1) + .Object + }) [1] "initialize" > new("seq") An object of class "seq" [1] 10.0000000 -4.5983522 0.1227316 |
Overwrite a function in a class
> tryCatch(setMethod("[", signature("integer"), function(x, i, + j, drop) print("howdy")), error = function(e) print("we failed")) [1] "we failed" |
Practice tryCatch
> options(warn = -2) > options(warn = 0) |
> setClass("MyInt", representation("integer")) [1] "MyInt" > setMethod("[", signature("MyInt"), function(x, i, j, drop) print("howdy")) [1] "[" > x <- new("MyInt", 5:7) > x[2] [1] "howdy" [1] "howdy" |