Hi R friends,
 
I'm still studying S4 classes and I have a question about slot assignment. Why 
would I have to use a special setter method [example 2 below] if I can assign 
data to a slot directly when I call new() [example 1 below]?
 
## first way to do it (the idiosyncratic way?)
setClass(Class = "TestClass", representation = representation(myDf = 
"data.frame"))
setGeneric(name = "doStuff", def = function(object, 
...){standardGeneric("doStuff")})
setMethod(f = "doStuff",
   signature = "TestClass",
   definition = function(object, ...) {
     return( obj...@mydf )
}) 
df_a <- data.frame(cbind(letters=letters, digits=runif(26)))
instance <- new(Class = "TestClass", myDf = df_a) # direct slot assignment. Is 
this bad? If so, why?
doStuff(instance)
 
## second way to do it (the R way?)
setClass(Class = "TestClass", representation = representation(myDf = 
"data.frame"))
setGeneric(name = "doStuff", def = function(object, 
...){standardGeneric("doStuff")})
setMethod(f = "doStuff",
   signature = "TestClass",
   definition = function(object, ...) {
     return( obj...@mydf )
}) 
setGeneric(name = "setDoStuff<-", def = function(object, 
value){standardGeneric("setDoStuff<-")})
setReplaceMethod(f = "setDoStuff",
   signature = "TestClass",
   definition = function(object, value) {
     obj...@mydf <- value
     return( object )
}) 
df_b <- data.frame(cbind(letters=LETTERS, digits=runif(26)))
instance <- new(Class = "TestClass")
setDoStuff(instance)<-df_b
doStuff(instance)

Thank you in advance for your replies!

Cheers!!
Albert-Jan

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a fresh water system, and public health, what have 
the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


      
        [[alternative HTML version deleted]]

______________________________________________
R-help@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.

Reply via email to