[R] overloading the generic primitive functions "+" and "["
Barry Rowlingson
b.rowlingson at lancaster.ac.uk
Thu Oct 28 15:38:37 CEST 2010
On Thu, Oct 28, 2010 at 2:12 PM, Martin Morgan <mtmorgan at fhcrc.org> wrote:
> Not so hard, eh? Though then like your S3 implementation this makes all
> 'Ops' (see ?Ops)
Except you have to re-run the set* things every R session:
> setClass("SS", "character")
> setMethod(Ops, c("SS", "SS"), function(e1, e2) paste(e1, e2))
> a=new("SS","hello")
> b=new("SS","world")
> a+b
[1] "hello world"
> q()
Save workspace image? [y/n/c]: y
...start R again...
[Previously saved workspace restored]
> a=new("SS","hello")
> b=new("SS","world")
> a+b
Error in a + b : non-numeric argument to binary operator
It seems the SS class is preserved but the method definition isn't.
Otherwise new("SS","hello") fails.
That's one of the things that confuses me about S4 - its use of
invisible global things. ls(all.names=TRUE) shows me the bits:
> ls(all.names=TRUE)
[1] "a" ".__C__SS" ".requireCachedGenerics"
It seems that .__C__SS is the class definition, and the
.requireCachedGenerics seems to imply I've done something with 'Ops':
> .requireCachedGenerics
[[1]]
[1] "Ops"
but doesn't actually store and restore my definition.
A bug? I dunno. Version 2.10.1 if anyone cares. I don't. I'll just go
back to my S3 method which is just as simple and works when I restore
the .RData I saved things to. Each to their own!
Barry
More information about the R-help
mailing list