setClass("Cohort", representation( details = "data.frame", centre = "character" ) ) w = c(32, 39, 33, 66, 24) h = c(1.4, 1.47, 1.47, 1.58, 1.25) coh_s4 = new("Cohort", details = data.frame(weight = w, height = h), centre = "NCL" )
Following the Cohort
example in the notes, suppose we want to make a generic for the mean
function.
Using the isGeneric
function, determine if the mean
function is an S4 generic. If not, use setGeneric
to create an S4 generic.
isGeneric("mean") setGeneric("mean")
setMethod
, create a mean
method for the Cohort
class.^[Be careful to match the arguments.]setMethod("mean", signature = c("Cohort"), definition = function(x, ...) { m1 = mean(x@details[, 1], ...) m2 = mean(x@details[, 2], ...) return(c(m1, m2)) } )
sd
function.isGeneric("sd") setGeneric("sd") setMethod("sd", signature = c("Cohort"), definition = function(x, na.rm = FALSE) { m1 = sd(x@details[, 1], na.rm = na.rm) m2 = sd(x@details[, 2], na.rm = na.rm) return(c(m1, m2)) } )
Create a summary
method for the cohort
class
Use isGeneric
to determine if an S4 generic exists.
setGeneric
to set the generic method (if necessary).isGeneric("summary") setGeneric("summary") setMethod("summary", signature = c("Cohort"), definition = function(object, ...) { summary(object@details) } )
hist
method for the cohort
class. When the hist
function is called on a cohort
, it should produce a single plot showing two histograms - one for height and another for weight.isGeneric("hist") setGeneric("hist") setMethod("hist", signature = c("Cohort"), definition = function(x, ...) { op = par(mfrow = c(1, 2)) hist(x@details[, 1], main = "Weight", ...) hist(x@details[, 2], main = "Height", ...) par(op) } )
[
method for the cohort
class. This method should return a cohort
object, but with the relevant rows sub setted.isGeneric("[") getGeneric("[") ## Can you determine what drop does? setMethod("[", signature = c("Cohort"), definition = function(x, i, j, ..., drop = TRUE) { x@details = x@details[i, j, ..., drop = drop] x } )
<-
method for the cohort
class. This method should allow us to replace values in the details
data frame.isGeneric("[<-") setGeneric("[<-") setMethod("[<-", signature = c("Cohort"), definition = function(x, i, j, value) { x@details[i, j] = value x } ) coh_s4[1, ] = 5
Solutions are contained within the course package
library("jrAdvGgplot2") vignette("solutions3", package = "jrAdvGgplot2")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.