R - S3 class: basics

15 Oct 2017

http://www.cyclismo.org/tutorial/R/s3Classes.html

http://adv-r.had.co.nz/S3.html

Example of constructor function for S3 classes

foo <- function(x) {
  if (!is.numeric(x)) stop("X must be numeric")
  structure(list(x), class = "foo")
}

Example of S3 classe creation and function:

NorthAmerican <- function(eatsBreakfast=TRUE,myFavorite="cereal")
{
        me <- list(
                hasBreakfast = eatsBreakfast,
                favoriteBreakfast = myFavorite
       )
        ## Set the name for the class
        class(me) <- append(class(me),"NorthAmerican")
        return(me)
}

setHasBreakfast <- function(elObjeto, newValue)
        {
                print("Calling the base setHasBreakfast function")
                UseMethod("setHasBreakfast",elObjeto)
                print("Note this is not executed!")
        }

setHasBreakfast.default <- function(elObjeto, newValue)
        {
                print("You screwed up. I do not know how to handle this object.")
                return(elObjeto)
        }


setHasBreakfast.NorthAmerican <- function(elObjeto, newValue)
        {
                print("In setHasBreakfast.NorthAmerican and setting the value")
                elObjeto$hasBreakfast <- newValue
                return(elObjeto)
        }


Mexican <- function(eatsBreakfast=TRUE,myFavorite="los huevos")
{

        me <- NorthAmerican(eatsBreakfast,myFavorite)

        ## Add the name for the class
        class(me) <- append(class(me),"Mexican")
        return(me)
}

[ R  class  ]