Last active
January 8, 2016 04:45
-
-
Save ncarchedi/7255306 to your computer and use it in GitHub Desktop.
Script to help understanding of S3 object-oriented programming in R using classes and methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Script to help understanding of S3 object-oriented programming | |
# in R using classes and methods | |
# Constructor functions for various classes of animal | |
pig <- function() structure(list(), class="pig") | |
dog <- function() structure(list(), class="dog") | |
cat <- function() structure(list(), class="cat") | |
# Generic makeSound function | |
makeSound <- function(x) UseMethod("makeSound") | |
# Methods for each class of animal plus a default method | |
makeSound.pig <- function(x) { | |
message(paste("A", class(x), "named", substitute(x), "goes oink!")) | |
} | |
makeSound.dog <- function(x) { | |
message(paste("A", class(x), "named", substitute(x), "goes woof!")) | |
} | |
makeSound.cat <- function(x) { | |
message(paste("A", class(x), "named", substitute(x), "goes meow!")) | |
} | |
makeSound.default <- function(x) { | |
message(paste("An animal named", substitute(x), "makes a sound, but I'm not sure what sound it makes without knowing what type of animal it is!")) | |
} | |
david <- pig() | |
larry <- dog() | |
jason <- cat() | |
terry <- 10 | |
nick <- dog() | |
trevor <- "hello" | |
carol <- pig() | |
makeSound(david) | |
makeSound(larry) | |
makeSound(jason) | |
makeSound(terry) | |
makeSound(nick) | |
makeSound(trevor) | |
makeSound(carol) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For a slightly cleaner version, see https://gist.github.com/ncarchedi/7279167