[R] Set without argument

Christophe Genolini cgenolin at u-paris10.fr
Tue Feb 26 22:45:51 CET 2008


Hi Martin

What do you think of the following code ?

A <- 1

imputeMyObj <- function(x){
  xImp <- 3 #Calcul for Imputation of x
  nam<-deparse(substitute(x))
  assign(nam,xImp,envir=parent.frame())
}
imputeMyObj(A)
A

I guess it is not usual, but do you think it is 'bad' programming or 
will have side effect that I do not see ?

Christophe

> 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.
>>     
>
>



More information about the R-help mailing list