[R] How to change the value of a class slot

Ross Boylan ross at biostat.ucsf.edu
Thu Jun 9 21:04:21 CEST 2005


On Wed, 2005-06-08 at 09:13 +0200, Uwe Ligges wrote:
[extensive deletions.  Discussion concerned my desire to have a function change the value
 of an object in a way that had effects outside of the function, without returning the object.]

> >>You have to think about scoping rules and it 
> >>will be clear that the approach you are expecting is not a clean one in S.
> > 
> > Could you say a bit more about that?  
> 
> I meant the following simple example (not related to any object oriented 
> programming from the S point of view, but maybe well from your point of 
> view?):
> 
> Say you want a function foo() that simply incements the argument:
> 
> a <- 1
> foo(a)
> a # now is 2
> 
> But what happens if there is (more than) one "a" (in different 
> environments), but no "a" in the environment foo(a) is called from. 
> Which "a" do you want to change in this case? Seems to be rather dangerous.
> 
> Uwe Ligges
> 
I believe your example assumes that foo is updating the outer a by
"cheating" and directly modifying enclosing environments.  (I figure it
also needs to get the name of its actual argument to do this, which
would also involve slightly dirty tricks.) This does seem to be the only
way to do it in standard R.

In contrast, I wanted something like
foo<-function(formalArg){ 
  formalArg <- new value
  return something  else
}
so that if I call foo(a), a has the new value after the call.
Unfortunately for me, that doesn't work.  Call-by-value semantics imply
that it can't.




More information about the R-help mailing list