Skip to content

Instantly share code, notes, and snippets.

@ashander
Last active May 12, 2016 17:25
Show Gist options
  • Save ashander/261b1d2d6bf19f1f21b57c6f533ee6c2 to your computer and use it in GitHub Desktop.
Save ashander/261b1d2d6bf19f1f21b57c6f533ee6c2 to your computer and use it in GitHub Desktop.
Rephrased example from Advanced R of method dispatch (http://adv-r.had.co.nz/S3.html)
## example from http://adv-r.had.co.nz/S3.html
newmean <- function (x, ...) {
UseMethod("newmean", x)
}
newmean.numeric <- function(x, ...) sum(x) / length(x)
newmean.data.frame <- function(x, ...) sapply(x, mean, ...)
newmean.matrix <- function(x, ...) apply(x, 2, mean)
#numeric a
a <- c(1, 2, 6)
newmean(a)
#data.frame a
a_df <- expand.grid(1:3, 100:103)
newmean(a_df)
#matrix a
a_m <- matrix(1:30, nrow=5)
newmean(a_m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment