Skip to content

Instantly share code, notes, and snippets.

@haxney
Created August 2, 2012 20:12
Show Gist options
  • Save haxney/3240247 to your computer and use it in GitHub Desktop.
Save haxney/3240247 to your computer and use it in GitHub Desktop.
Dispatching on generic methods in R
## Reverse the order of the arguments.
foo <- function(iterVar, quux) {
UseMethod("foo", object=quux)
}
## Need to be reversed in the implementation as well
foo.myClass <- function(iterVar, quux) {
## `paste()` combines its arguments into a single string.
paste("within foo.myClass. quux:", quux, "iterVar:", iterVar)
}
## Now call `lapply()` again
lapply(listOfStuff, foo, bar)
## <= list("within foo.myClass. quux: any old object iterVar: a",
## "within foo.myClass. quux: any old object iterVar: b"
## ## etc.
## )
## Because `lapply()` Calls `foo()` like this:
foo(listOfStuff[i], bar)
## <- is the assignment operator, equivalent to `=` in most other languages
foo <- function(quux, iterVar) {
UseMethod("foo")
}
## Restore `foo()` and its implementation back to their good old days.
foo <- function(quux, iterVar) {
UseMethod("foo")
}
foo.myClass <- function(quux, iterVar) {
paste("within foo.myClass. quux:", quux, "iterVar:", iterVar)
}
lapply(listOfStuff, foo, quux=bar)
## means `foo()` is now called like this:
foo(listOfStuff[i], quux=bar)
## Define a list
listOfStuff <- list("a", "b", "c", "easy as", 1, 2, 3)
applied <- lapply(listOfStuff, identity)
identical(listOfStuff, applied) ## => TRUE
## `lapply()` can be given extra arguments which are passed on to the iteration
## function
lapply(listOfStuff, foo, bar)
## Results in:
##
## Error in UseMethod("foo") :
## no applicable method for 'foo' applied to an object of class "character"
## That's because `lapply()` called `foo` like this:
foo(listOfStuff[i], bar)
bar <- "any old object"
attr(bar, "class") <- "myClass"
## Objects can even have multiple classes (`c()` creates a vector/list of its
## arguments):
attr(bar, "class") <- c("myClass", "otherClass")
## Call the `foo` method on `bar`
foo(bar, "blank for now")
## fails with:
##
## Error in UseMethod("foo") :
## no applicable method for 'foo' applied to an object of class "c('myClass', 'otherClass')"
## An implementation of the method needs to be defined:
foo.myClass <- function(quux, iterVar) {
## `paste()` combines its arguments into a single string.
paste("within foo.myClass. quux:", quux, "iterVar:", iterVar)
}
## If we try calling `foo()` again...
foo(bar, "blank for now")
## => "within foo.myClass. quux: any old object iterVar: blank for now"
## Woot!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment