Search code examples
rfunctionclassgeneric-function

Generic function called via second argument of foo(x, bar) in R


I want to make a generic function predict() for 'foo' class in R so that it is invoked when second argument of predict() is of class 'foo':

class(y.foo) <- "foo"

predict(x, y.foo)

Is it possible? How to do it?


Solution

  • Try this. Here our foo method just outputs "foo" and in the real code it would be replaced with whatever foo method you have:

    predict <- function(x, foo = NULL, ...) UseMethod("predict", foo)
    predict.foo <- function(x, foo, ...) "foo" # replace with your foo method
    predict.default <- function(x, foo = NULL, ...) if (is.null(foo)) 
             stats::predict(x, ...) else stats::predict(x, foo, ...)
    

    Now test it out:

    y.foo <- 1
    class(y.foo) <- "foo"
    predict(0, y.foo)
    ## [1] "foo"
    
    fm <- lm(demand ~ Time, BOD)
    
    predict(fm)
    ##        1        2        3        4        5        6 
    ## 10.24286 11.96429 13.68571 15.40714 17.12857 20.57143 
    
    predict(fm, newdata = list(Time = 1:2))
    ##        1        2 
    ## 10.24286 11.96429 
    
    predict(fm, list(Time = 1:2)) # same
    ##        1        2 
    ## 10.24286 11.96429