正如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!"