我不确定这是否会对您有所帮助,或者这是否可以满足您的需求。但是为什么不声明 a并为andgeneric method
定义方法呢?这是一个虚拟/愚蠢的例子:matrix
data.frame
# generic method
my_fun <- function(x, ...) {
UseMethod("my_fun", x)
}
# default action
my_fun.default <- function(x, ...) {
cx <- class(x)
stop(paste("No method defined for class", cx))
}
# method for object of class data.frame
my_fun.data.frame <- function(x, ...) {
print("in data.frame")
tapply(x[,1], x[,2], sum)
}
# method for object of class matrix
my_fun.matrix <- function(x, ...) {
print("in matrix")
my_fun(as.data.frame(x))
}
# dummy example
df <- data.frame(x=1:5, y=c(1,1,1,2,2))
mm <- as.matrix(df)
> my_fun(df)
# [1] "in data.frame"
# 1 2
# 6 9
> my_fun(mm)
# [1] "in matrix"
# [1] "in data.frame"
# 1 2
# 6 9
> my_fun(as.list(df))
# Error in my_fun.default(as.list(df)) : No method defined for class list