1

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

Martin
  • 113
  • 1
  • 1
  • 6
  • if you dont have a method for `class(x)`, the default method is used, so you can add that line to the default method I suppose – rawr Jun 18 '16 at 00:28
  • Thanks for the reply. But the default method handels only matrices and is the wrong one. I need somehow come to the formula method and do not want to add another method for character... – Martin Jun 18 '16 at 07:33

1 Answers1

1

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
rawr
  • 20,481
  • 4
  • 44
  • 78