Christophe Genolini <cgenolin at u-paris10.fr> writes:
> Hi the list,
>
> I am defining S4 objet. Is it possbile to define a method that change
> the slot of an object without using <- ?
> My object contain a numeric and a matrix. At some point, I would like to
> impute the missing value in the matrix. So I would like to use something
> like :
>
> -----------------
>
setClass("MyObj",representation(time="numeric",traj="matrix"))
> a <- new("MyObj",time=3,traj=matrix(c(1:6,NA,8:12),ncol=3))
> imputeMyObj(a)
> -----------------
Hi Christophe --
The 'usual' way to write the above code is
> a <- imputeMyObj(a)
with imputeMyObj designed to take a 'MyObj' as it's argument, and
return a modified 'MyObj' (that the user can assign to 'a', if
they
like). Inside imputeMyObj, the developer would, in the end, write
something like
impuateMyObj <- function(obj) {
# calculate imputed values 'imp'
slot(obj, "traj") <- imp
obj
}
A better design would have a 'setter' method, minimally
> setGeneric("traj<-",
+ function(object, ..., value)
standardGeneric("traj<-"))
[1] "traj<-"> setReplaceMethod("traj",
+ signature=signature(
+ object="MyObj",
+ value="matrix"),
+ function(object, ..., value) {
+ slot(object, "traj") <- value
+ object
+ })
[1] "traj<-"
and then the impute code would have
impuateMyObj <- function(obj) {
# calculate imputed values 'imp'
traj(obj) <- imp
obj
}
It's possible to design 'MyObj' so that it can be modified in-place
(e.g., storing data in a slot of class 'environment', which has
reference-like behavior) but this will probably surprise both you and
the user.
Martin
> I find 'setTime<-' to change le slot time, but it can not work
in the
> case of imputeMyObs since this mehod does not need a value...
>
> Any solution ?
>
> Thanks
>
> 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.
--
Martin Morgan
Computational Biology / Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N.
PO Box 19024 Seattle, WA 98109
Location: Arnold Building M2 B169
Phone: (206) 667-2793