>我在R中定义了以下内容:
plotWaterfall <- function(x, ...) UseMethod("plotWaterfall")
plotWaterfall.default <- function(x, ...) {print("Default method does nothing")}
plotWaterfall.vector <- function(x, ...) {print("Vector method does something")}
现在,如果我测试以下示例:
x<-c(1,2,3)
plotWaterfall(x)
它将打印"默认方法不执行任何操作",指示 S3 框架与默认方法匹配,而不是矢量方法。这是为什么呢?
这是因为向量的类是numeric
. 所以你必须这样做:
plotWaterfall.numeric <- function(x, ...) {print("Numeric vector")}
plotWaterfall(x)
[1] "Numeric vector"
您可以使用 class()
函数确定对象的类:
class(x)
[1] "numeric"
此行为在 ?UseMethod
的帮助中描述:
方法调度基于第一个类进行 泛型函数或作为 参数到使用方法