From janko.thyson.rstuff at googlemail.com  Mon May  2 18:03:27 2011
From: janko.thyson.rstuff at googlemail.com (Janko Thyson)
Date: Mon, 02 May 2011 18:03:27 +0200
Subject: [Rd] Replacing '.self' with an .Rda image of '.self' from within a
	method?
Message-ID: <4DBED5CF.8030605@googlemail.com>

Dear list,

Is it possible to update or reassign '.self' with an image of '.self' 
(e.g. a locally stored .Rda file) from within a method?

I know that this might sound akward, but here's the use case:
1) Ref Class Definition
     setRefClass(Class="Test",
         fields=list(A="character", B="character"),
         methods=list(importImage=function(path){
             variable <- load(path)
             expr <- paste("assign('", variable, "',", variable, ", 
envir=.self)", sep="")
             eval(parse(text=expr))
         }
     )
2) Initialize Method Definition
     setMethod(
         f="initialize",
         signature=signature(.Object="Test"),
         definition=function(
             .Object,
             path=NULL
     ){
         obj <- callNextMethod(.Object)
         if(!is.null(path){
             obj$importImage(path=path)
         }
         return(obj)
     }
3) Intended and "Extended" Use
     Method 'importImage' was originally intended to read either an 
object of name 'A' or 'B' from a respective path and overwrite the 
respective fields in an obj of class 'Test'.
     Now I wondered how I could "reassign"/update the object of class 
'Test' itself by reading a respective .Rda image of an object of class 
'Test' from within 'obj$importImage()'.
     The way I've written 'importImage()', it did not work. Yet I wonder 
if it's possible.
4) My Workaround (but I'm looking for something more elegantly)
     In the class definition:
     [...]
     methods=list(importImage=function(path){
             variable <- load(path)
             if(variable != ".self"){
                 expr <- paste("assign('", variable, "',", variable, ", 
envir=.self)", sep="")
                 eval(parse(text=expr))
                 return(TRUE)
             } else {
                 return(.self)
             }
     })
     [...]

     In the initialize method:
     setMethod(
         f="initialize",
         signature=signature(.Object="Test"),
         definition=function(
             .Object,
             path=NULL
     ){
         obj <- callNextMethod(.Object)
         if(!is.null(path){
             rslt <- obj$importImage(path=path)
             if(!is.logical(rslt)){
                 obj <- rslt
             }
         }
         return(obj)
     }

Thanks for any comments,
Janko



[Rd] Replacing '.self' with an .Rda image of '.self' from within a method?
Janko Thyson