[R] Standard method for S4 object

Martin Morgan mtmorgan at fhcrc.org
Sun Feb 24 17:48:20 CET 2008


Christophe Genolini wrote:
>> /I think your question should be more relevant on Rdev./
> ok, I will
>> Personnally I would find stuff like "names",  "$", "$<-", or "[" 
>> useful as these are usual operation with S3 objects.
> Is it possible in S4 to define "$<-" ? If there is a slot name 'a' in 

Possible yes, see below. Usual? It implies to the user that this is a 
list- or data.frame-like object (where $ is used most commonly). Maybe 
your object is not like that? It also seems like a short step from 
direct slot access (although it doesn't have to be), which might be 
breaking the abstraction layer that object orientation provides. And it 
shifts the responsibility for confirming that 'name' is a slot, and 
dispatching on different values of 'name' (e.g. for some slots perhaps 
one doesn't want to allow access, and then the code inside the '$' 
method has to check that), back to the developer (instead of allowing 
the method definition and dispatch to do its work). Generally these seem 
like backward steps to me.

 > setClass("A", representation(x="numeric"))
[1] "A"
 > setReplaceMethod("$",
+           signature=signature(
+             x="A",
+             name="ANY",
+             value="ANY"),
+           function(x, name, value) {
+             slot(x, name) <- value
+             x
+           })
[1] "$<-"
 > a <- new("A")
 > a$x <- 1:5
 > a
An object of class "A"
Slot "x":
[1] 1 2 3 4 5

> object 'B', I find (in "S4 in 15 pages more or less")
> 
> setGeneric("a<-", function(x, value) standardGeneric("a<-"))
> setReplaceMethod("a", .....
> 
> Then we can use
> 
> obj <- new("B")
> a(obj)<- 3
> 
> But I did not find how to define
> 
> obj$a <- 3
> 
> Is it possible ? Is it the 'usual' way ?
> 
> 
> Christophe
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list