ramazon-s3type-conversionmethod-dispatch

Type conversion before dispatch takes place


I am defining a generic function

genfun <- function(x, ...)
    UseMethod("genfun")

which should have tow instances: genfun.default (if x is a matrix) genfun.formula (if x is a formula)

This works fine, but now I would like to have that before the dispatch takes place, that if x is a charcter string it is forced to be a formula.

Unfortunately the following does not work

genfun <- function(x, ...) {
    if (is.character(x)) x <- as.formula(x)
    UseMethod("rlasso")
}

Is there a way to handle this without defining a further instance like genfun.character?

Thanks a lot for your help in advance!

Best,

Martin


Solution

  • I was thinking something like this (although the proper way would be to define another method).

    genfun <- function(x, ...)
      UseMethod('genfun')
    
    genfun.default <- function(x, ...) {
      if (is.character(x)) {
        x <- as.formula(x)
        return(genfun(x))
      }
      dim(x)
    }
    
    genfun.formula <- function(x, ...) {
      message('using formula method')
      ## do something
    }
    
    
    genfun(mtcars)
    # [1] 32 11
    
    genfun(y ~ x)
    # using formula method
    
    genfun('y ~ x')
    # using formula method