[R] changing function argument

Thomas Mang thomas.mang at fiwi.at
Fri Mar 13 10:29:24 CET 2009


Dieter Menne wrote:
> Thomas Mang <thomas.mang <at> fiwi.at> writes:
> 
>> I wonder if the following is possible in R:
>>
>> Suppose a function takes an argument, and wants to modify this argument 
>> so that the change is visible _at the call side_. It would be what is 
>> for example known as pass-by-reference-to-non-const in C++.
>>
>> test <- function(x)
>> {
>>   x <- 10
>>   ...
>>   return (somethingElse) # I do NOT want having to return x
>> }
>>
>> number = 5
>> test(number)
>> stopifnot(number == 10)
>>
>> Is there some trick with scoping rules and maybe <<- to achieve this ?
> 
> Yes, it is possible. No, don't do it (coming from the c++ world, I understand
> your temptation). Try to look for "assign" to see the attached flames.

Hi,
Well the point is I really really want to do it - and believe me, I know 
what I am doing ;) (for that matter, this is done solely in 
implementation code - of course I wouldn't do such a thing in a publicly 
used interface).
I know assign, and I suppose the trick is something to pass the name of 
the variable at the call side, as well as the environment of the call 
side, as additional argument to my test-function, so it knows what to 
change where. Is that correct ? Is there some more short-hand / direct / 
elegant way of achieving my goal ?

thanks,
Thomas




More information about the R-help mailing list