1

I have defined the following in R:

plotWaterfall         <- function(x, ...) UseMethod("plotWaterfall")
plotWaterfall.default <- function(x, ...) {print("Default method does nothing")}
plotWaterfall.vector  <- function(x, ...) {print("Vector method does something")}

Now if I test the following example:

x<-c(1,2,3)
plotWaterfall(x)

it will print "Default method does nothing" indicating that the S3 framework matches the default method instead of the vector method. Now why is that?

4

1 回答 1

2

这是因为你的向量的类是numeric. 所以你必须这样做:

plotWaterfall.numeric  <- function(x, ...) {print("Numeric vector")}

plotWaterfall(x)
[1] "Numeric vector"

您可以使用以下函数确定对象的类class()

class(x)
[1] "numeric"

帮助中描述了此行为?UseMethod

方法分派基于泛型函数的第一个参数的类或作为 UseMethod 的参数提供的对象的类

于 2012-12-07T10:14:42.813 回答