Skip to content

Instantly share code, notes, and snippets.

@ncarchedi
Last active January 8, 2016 04:45
Show Gist options
  • Save ncarchedi/7255306 to your computer and use it in GitHub Desktop.
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
# 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)
@ncarchedi
Copy link
Author

For a slightly cleaner version, see https://gist.github.com/ncarchedi/7279167

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment