Search code examples
rr-s3method-dispatch

Error in UseMethod when Method Dispatching


I have tried the following code to create a method but when I use the generic function named "tutu" I receive the following error while the other functions (tutu.num and tutu.ch) work. Please can you help me to understand where is the mistake? I would expect that the "tutu" function recognize the class and use the appropriate method of the function that in the example is tutu.num. Thank you!

tutu.num<-function(x){x*100}
tutu.ch<-function(x){paste(x,"OK")}
tutu<-function(x){
  UseMethod("tutu")
}
vot<-1:5
tutu(vot)

Error in UseMethod("tutu") : no applicable method for 'tutu' applied to an object of class "c('integer', 'numeric')"


Solution

  • You need to include the full class name after the period in your methods. In your example, the variable vot has class "numeric", but you only have methods defined for the classes "num" and "ch", neither of which exist. You need to define tutu.numeric and tutu.character. You can also define a tutu.default to handle objects of other unspecified classes:

    tutu           <- function(x) UseMethod("tutu")
    tutu.default   <- function(x) return(NULL)
    tutu.numeric   <- function(x) x * 100
    tutu.character <- function(x) paste(x, "OK")
    
    tutu(1:5)
    #> [1] 100 200 300 400 500
    
    tutu("method dispatch")
    #> [1] "method dispatch OK"
    
    tutu(data.frame(a = 1, b = 2))
    #> NULL