[R] Method for $

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Nov 22 09:39:32 CET 2005


On Fri, 18 Nov 2005, Ulrike Grömping wrote:

> From: Duncan Temple Lang <duncan at wald.ucdavis.edu>

[...]
>> For the record, the problem you are experiencing is that
>> you are not using the same argument names in your
>> method as the function "$" uses. Hence there is a mismatch.
>> Use
>> setMethod("$", signature(x="myclass"), function(x, name){
>>   slot(x, name)
>> } )
>>
>> i.e. rather than slotname as the second argument, use name
>> as that is what $ uses.
>
> Thanks very much for clarifying that. I just wasn't aware of the 
> argument names of $. It's obvious from the help file, once you know what 
> to look for, but ...

`For the record', this is rather misleading.  $ is a primitive function in 
R, and does _not_ have argument names (it uses only positional matching 
like all primitive functions).  To check this, try

xx <- list(a=1, b=2)
`$`(y=xx, zz="b")

which is perfectly valid R and works just like xx$b.  Hence there is no 
reason for the help page to specify argument names (and it does in fact 
explain that they are not used).

However, the S4 model needs argument names, and so when setting S4 methods 
for primitive functions one needs to use the argument names which it 
_assumes_.  Sometimes the only way to find those out is to read the code. 
They are in src/library/methods/R/BasicFunsList.R which contains

"$" = function(x, name)
{
     name <- as.character(substitute(name))
     standardGeneric("$")
}

S3 methods for primitives do not need to match argument names, fortunately 
as Duncan TL has just added an S3 method with the (mis-matching) arguments

> args(`$.DLLInfo`)
function (x, i, ...)

Since there are no argument names for the generic, the QC tools do not 
check such cases.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595


More information about the R-help mailing list