0

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?

Tim
  • 7,075
  • 6
  • 29
  • 58
  • Please provide more information about what you are trying to do. What is the class of `x`? What is your use case for doing this? It is possible to do this with S4 classes but that might be overkill. The more information you provide the easier it will be to help you. – Andrie Jul 04 '14 at 16:02
  • Classic S3 dispatching only happens on the class of the first object. In your case, what is `class(x)`? – MrFlick Jul 04 '14 at 16:58
  • Class of x is numeric. I understand that the only possibility is to make predict.numeric that checks if the class of second argument is "foo"? – Tim Jul 04 '14 at 22:58
  • Why would you be passing numeric values are the first parameter to `predict()`? In all other cases uses the "model" comes first. – MrFlick Jul 05 '14 at 03:20
  • @MrFlick Maybe you're right and I should just stick to classic predict syntax. – Tim Jul 06 '14 at 08:39

1 Answers1

1

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 
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341