在R中,为什么在绘图时关键字data和formula关键字的顺序很重要?我认为,使用命名参数命令不应该重要...
有关我的意思的示例,请查看此代码:
library(MASS)
data(menarche)
# Correct formulation (apparently):
plot(formula=Menarche/Total ~ Age, data=menarche)
# In contrast, note how the following returns an error:
plot(data=menarche, formula=Menarche/Total ~ Age)
Run Code Online (Sandbox Code Playgroud)
这只是plot函数的一个怪癖,还是在其他函数中也表现出这种行为?
Rei*_*son 13
它与S3泛型的S3方法有关plot().S3调度基础上,第一个参数但是确切的功能,是因为复杂的方法formula是允许作为特殊例外,从通常的通用参数plot(),这是x与y加...:
> args(plot)
function (x, y, ...)
NULL
Run Code Online (Sandbox Code Playgroud)
因此,在第一种情况下发生的是该plot.formula()方法被运行,因为提供的第一个参数是一个公式,并且它匹配的参数plot.formula()
> args(graphics:::plot.formula)
function (formula, data = parent.frame(), ..., subset, ylab = varnames[response],
ask = dev.interactive())
NULL
Run Code Online (Sandbox Code Playgroud)
例如:
> 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...]
Run Code Online (Sandbox Code Playgroud)
相反,当您调用时plot(data=menarche, formula=Menarche/Total ~ Age),第一个参数是数据框,因此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)
Run Code Online (Sandbox Code Playgroud)
但是因为该方法需要一个x你没有提供的参数,所以会得到关于缺失的错误x.
所以从某种意义上说,命名参数的排序不是也不应该重要,但是当S3泛型处于播放方法时,调度首先要确定将哪个方法传递给参数,然后提供参数 - 而不是排序 - 是经常会让你失望的东西,特别是在将这些formula方法与其他非formula方法混合时.
| 归档时间: |
|
| 查看次数: |
583 次 |
| 最近记录: |