I gave this talk at our graduate student computing club. It was an informal introduction to object-oriented programming in R, focusing on S4, with a brief comparison to Python classes. Examples on github: https://github.com/alyssafrazee/cards
piece of data associated with the object • “method” = procedure/function associated with the object I got this from Wikipedia (and remembering stuff from when I took CS101 in 2008)
your own way of storing data. Famous R examples: lm SummarizedExperiment fmridata Note: some people are anti-OOP: http://c2. com/cgi/wiki?ArgumentsAgainstOop
#' @slot suit Is this card a spade, club, diamond, or heart? #' @slot number The card’s value. Can be 2-10, ‘J’, ‘Q’, ‘K’, or ‘A’ #’ @slot trump Is the card a trump card? Boolean. #' #' @exportClass Card setClass("Card", representation( suit = "character", number = "numeric", trump = "logical") ) AllClass.R
the same value and color as the given card #' #' @param card Object of class “Card” #' @export find_pair = function(card){ new_suit = switch(card@suit, diamonds = ‘hearts’, hearts = ‘diamonds’, spades = ‘clubs’, clubs = ‘spades’) return(new(‘Card’, suit = new_suit, number = card@number, trump=FALSE)) } find_pair.R
probably the easiest choice if the function name is unique. • Extend or create a generic function, then create a way for that function to work with your class of object. ◦ required if you need to make a base function like “plot” work with your object ◦ optional if function name is unique -- consider whether the function might be useful for existing or future classes of objects
things get complicated VERY quickly • S3 and S4 classes working together; documentation, etc • questions? discussion? • R example on github: https://github. com/alyssafrazee/cards