Janko Thyson
2011-May-02 16:03 UTC
[Rd] Replacing '.self' with an .Rda image of '.self' from within a method?
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
Reasonably Related Threads
- Reference Classes: replacing '.self' with an .Rda image of '.self' from within a method? (was replacing '.self' with an .Rda image of '.self' from within a method?)
- Ref Classes: bug with using '.self' within initialize methods?
- Bug or feature: using "ANY" as a generic field class (was: '[R] Is there a (virtual) class that all R objects inherit from?)
- reference classes: question on inheritance
- setting invalid fields on reference classes sometimes allowed