[Rd] Argument mismatches in S3 generic and method
William Dunlap
wdunlap at tibco.com
Wed Jun 9 20:03:12 CEST 2010
The way R treats the first argument to an S3 method
which uses a different name for the argument than
the generic depends on whether there is a ... in the
argument list. If there is is no ellipsis then
the call cannot tag the argument with either name
but an untagged first argument works:
> zNoDots <- function(x) UseMethod("zNoDots")
> zNoDots.foo <- function(fooObject) { cat("zNoDots.foo: fooObject=")
; dput(fooObject) }
> foo <- structure(1:4, class="foo")
> x <- "x in .GlobalEnv"
> zNoDots(foo)
zNoDots.foo: fooObject=structure(1:4, class = "foo")
> zNoDots(x=foo)
zNoDots.foo: fooObject=Error in .Call("R_isS4Object", object, PACKAGE
= "base") :
'object' is missing
> zNoDots(fooObject=foo)
Error in zNoDots(fooObject = foo) : unused argument(s) (fooObject =
foo)
If there is an ellipsis in the function definition
the call can tag the argument by the name given in
the method, but not by the generic's name for the
argument (and an untagged argument works here also):
> zDots <- function(x,...) UseMethod("zDots")
> zDots.foo <- function(fooObject,...) { cat("zDots.foo: fooObject=")
; dput(fooObject) }
> zDots(foo)
zDots.foo: fooObject=structure(1:4, class = "foo")
> zDots(x=foo)
zDots.foo: fooObject=Error in .Call("R_isS4Object", object, PACKAGE =
"base") :
'object' is missing
> zDots(fooObject=foo)
zDots.foo: fooObject=structure(1:4, class = "foo")
Is there a deep reason for this difference or is it just
an accident of implementation?
The question came up when someone asked me why
var.test(x=y~group,
data=data.frame(y=1:5,group=letters[c(1,1,1,2,2)]))
failed but leaving off the x= allowed it to work. var.test's
first argument is called "x" but var.test.formula's is "formula".
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
More information about the R-devel
mailing list