Skip to content

Instantly share code, notes, and snippets.

@kohske
Created January 24, 2012 08:30
Show Gist options
  • Save kohske/1668845 to your computer and use it in GitHub Desktop.
Save kohske/1668845 to your computer and use it in GitHub Desktop.
method_missing in R?
method.name <- "test"
eval(parse(text=sprintf('setGeneric("%s", function(object) standardGeneric("%s"))', method.name, method.name)))
setClass("cc", representation(x="numeric"))
setGeneric("pp", function(o) standardGeneric("pp"))
setMethod("pp", c("cc"), function(o) o@x)
setGeneric("qq", function(o) {
f <- deparse(match.call()[[1]])
if (!existsMethod(f, class(o)))
print("orz")
else
standardGeneric("qq")
})
c1 <- new("cc", x=1.5)
pp(c1)
qq(c1)
setClass("cc", representation(x="numeric"))
setGeneric("pp", function(o) standardGeneric("pp"))
setMethod("pp", c("cc"), function(o) o@x)
# hook missing method
method_missing <- function(cal) {
cal <- as.list(cal)
do.call("pp", cal[-1])
}
setGeneric("qq", function(o) {
f <- deparse(match.call()[[1]])
if (!existsMethod(f, class(o)))
method_missing(match.call())
else
standardGeneric("qq")
})
c1 <- new("cc", x=1.5)
pp(c1)
qq(c1)
@kohske
Copy link
Author

kohske commented Jan 24, 2012

環境をケアしないといけないのが面倒だけど。

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