On Fri, Mar 30, 2007 at 10:45:38PM +0200, cstrato wrote: > Dear all, > > Assume that I have an S4 class "MyClass" with a slot "myname", which > is initialized to: myname="" in method("initialize"): > myclass <- new("MyClass", myname="") > > Assume that class "MyClass" has a method "mymethod": > "mymethod.MyClass" <- > function(object, myname=character(0), ...) { > [EMAIL PROTECTED] <- myname; > #or: myName(object) <- myname > } > setMethod("mymethod", "MyClass", mymethod.MyClass); > > Furthermore, I have a replacement method: > setReplaceMethod("myName", signature(object="MyClass", value="character"), > function(object, value) { > [EMAIL PROTECTED] <- value; > return(object); > } > ) > > I know that it is possible to call: > myName(myclass) <- "newname" > > However, I want to replace the value of slot "myname" for object "myclass" > in method "mymethod": > mymethod(myclass, myname="newname") > > Sorrowly, the above code in method "mymethod" does not work. > > Is there a possibility to change the value of a slot in the method of a > class?
Yes, but to make the effect persistent (visible might be a more accurate description) that method must return the object being updated, and you must use the return value. R uses call by value semantics, so in the definition of mymethod.MyClass when you change object you only change a local copy. It needs to be "mymethod.MyClass" <- function(object, myname=character(0), ...) { [EMAIL PROTECTED] <- myname; object } Further, if you invoke it with mymethod(myclass, "new name") you will discover myclass is unchanged. You need myclass <- mymethod(myclass, "new name") You might consider using the R.oo package, which probably has semantics closer to what you're expecting. Alternately, you could study more about R and functional programming. Ross Boylan P.S. Regarding the follow up saying that this is the wrong list, the guide to mailing lists says of R-devel "This list is intended for questions and discussion about code development in R. Questions likely to prompt discussion unintelligible to non-programmers or topics that are too technical for R-help's audience should go to R-devel," The question seems to fall under this description to me, though I am not authoritative. It is true that further study would have disclosed what is going on. Since the same thing tripped me up too, I thought I'd share the answer. ______________________________________________ R-devel@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-devel