这与S3通用函数plot()
的S3方法相关。 S3根据第一个参数调度方法,但确切的功能很复杂,因为formula
被允许作为plot()
的通常通用参数x
和y
加上...
的特殊例外:
> args(plot)
function (x, y, ...)
NULL
因此,在第一种情况下发生的是,由于提供的第一个参数是公式,与
plot.formula()
的参数匹配,因此运行
plot.formula()
方法。
> args(graphics:::plot.formula)
function (formula, data = parent.frame(), ..., subset, ylab = varnames[response],
ask = dev.interactive())
NULL
例如:
> debugonce(graphics:::plot.formula)
> plot(formula=Menarche/Total ~ Age, data=menarche)
debugging in: plot.formula(formula = Menarche/Total ~ Age, data = menarche)
debug: {
m <- match.call(expand.dots = FALSE)
[...omitted...]
当您调用 plot(data=menarche, formula=Menarche/Total ~ Age)
时,第一个参数是数据框(data frame),因此会调用graphics:::plot.data.frame
方法:
> plot(data=menarche, formula=Menarche/Total ~ Age)
Error in is.data.frame(x) : argument "x" is missing, with no default
> traceback()
3: is.data.frame(x)
2: plot.data.frame(data = menarche, formula = Menarche/Total ~ Age)
1: plot(data = menarche, formula = Menarche/Total ~ Age)
但因为该方法需要一个参数x
,而您没有提供,所以会收到关于缺少x
的错误。
因此,在某种意义上,命名参数的顺序并不重要,也不应该重要,但当S3泛型参与时,方法调度首先会起作用,以决定将参数传递给哪个方法,然后提供的参数 - 而不是顺序 - 通常是容易出错的地方,特别是在混合使用formula
方法和其他非formula
方法时。
graphics:::plot.default(data=menarche, formula=Menarche/Total ~ Age)
和graphics:::plot.formula(data=menarche, formula=Menarche/Total ~ Age)
的区别是什么? - rawrgraphics:::plot.data.frame
astraceback()
shows it is this method that is actually being called.”翻译: @rawr对了,引起错误的不是顺序,而是S3分发(dispatch)在处理参数并将其分派到不同方法。然而,第一个应该是graphics:::plot.data.frame
,因为traceback()
显示实际被调用的是这个方法。 - Gavin Simpson