R:基于参数的S3方法分发

3

我有一个通用函数foo,根据给定的参数,我希望以三种不同的方式调用它。

foo <- function(...) UseMethod("foo")

#default
foo.default <- function(x, y, ...) {
#does some magic
print("this is the default method")
}

#formula
foo.formula <- function(formula, data = list(), ...) {
print("this is the formula method")
}

#data.frame
foo.data.frame <- function(data, x, y, ...) {
print("this is the data.frame method")
}

接下来,我将展示我对方法调度的期望,但输出结果在每次调用下面呈现...

mydata <- data.frame(x=c(1,2,3,4),y=c(5,6,7,8))

#ways to call default function
foo(x = mydata$x, y = mydata$y)
#[1] "this is the default method"

#ways to call formula
foo(formula = mydata$x~mydata$y)
#[1] "this is the formula method"
foo(formula = x~y, data = mydata)
#[1] "this is the formula method"
foo(data = mydata, formula = x~y)  #ERROR
#[1] "this is the data.frame method"

#ways to call data.frame method
foo(data = mydata, x = x, y = y)
#[1] "this is the data.frame method"
foo(x = x, y = y, data = mydata) #ERROR
#Error in foo(x = x, y = y, data = mydata) : object 'x' not found

据我所知,使用的方法取决于第一个参数的类。本质上,我希望方法分派取决于传递给通用函数foo的参数,而不是第一个参数。
我希望分派具有以下优先级:
如果存在formula参数,则使用formula方法(data参数应该是可选的)
然后,如果没有找到formula参数,如果存在data参数,则使用data.frame方法(需要x和y参数)
否则,foo将期望x和y参数,否则它将失败。
注意:
我希望避免以下方式定义通用函数foo
foo <- function(formula, data,...) UseMethod("foo")

虽然这样做可以解决我所有的问题(我相信除了最后一种情况外),但这将导致 devtools::check() 警告,因为某些 S3 函数的参数不同于通用函数,并且将不再保持一致性(特别是 foo.default 和 foo.data.frame)。而我不想包含缺失的参数,因为这些方法对这些参数没有用途。


2
在函数签名中,第一个命名参数是最重要的,而不是它们被调用的顺序。对于 foo(a,b) {...}foo(a = 1, b = 2)foo(b = 2, a = 1) 基于 a 的类别将分派到相同的方法。通常,您需要寻找多重分派,这仅在 S4 中可用,而不是 S3。 - Thomas
1个回答

2

正如Thomas所指出的那样,这不是S3类的标准行为。然而,如果您确实想坚持使用S3,您可以编写函数来"模仿"UseMethod的方式,尽管这可能不太美观,也不是您想要做的事情。尽管如此,这里有一个基于先捕获所有参数,然后检查是否存在所需参数类型的想法:

首先获取一些对象:

a <- 1; class(a) <- "Americano"
b <- 2; class(b) <- "Espresso"

让所涉及的函数使用点来捕获所有参数,然后按照您的喜好顺序检查参数类型的存在:

drink <- function(...){
  dots <- list(...)

  if(any(sapply(dots, function(cup) class(cup)=="Americano"))){
    drink.Americano(...)
    } else { # you can add more checks here to get a hierarchy
        # try to find appropriate method first if one exists, 
        # using the first element of the arguments as usual
        tryCatch(get(paste0("drink.", class(dots[[1]])))(), 
        # if no appropriate method is found, try the default method:
             error = function(e) drink.default(...)) 
  }
}

drink.Americano <- function(...) print("Hmm, gimme more!")
drink.Espresso <- function(...) print("Tripple, please!")
drink.default <- function(...) print("Any caffeine in there?")

drink(a) # "Americano", dispatch hard-coded.
# [1] "Hmm, gimme more!"
drink(b) # "Espresso", not hard-coded, but correct dispatch anyway
# [1] "Tripple, please!"
drink("sthelse") # Dispatches to default method
# [1] "Any caffeine in there?"
drink(a,b,"c")
# [1] "Hmm, gimme more!"
drink(b,"c", a)
# [1] "Hmm, gimme more!"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接