[R] How can I assign an argument to transfer whether by ref or by value?

Marc Schwartz MSchwartz at mn.rr.com
Sun Nov 6 20:26:17 CET 2005


Adai,

Duncan posted a reply to Xiaofan's query, indicating that R is generally
based upon pass by value.

The difference being that within R, either explicit values or explicit
copies of objects are passed as function arguments, as opposed to
passing a memory location reference to the original value or object.

In C, this would be the difference between passing a value or named
variable versus passing a memory pointer to the value or named variable.

Consistent with R's lexical scoping, when for example an object is
passed to a function as an argument, a copy of the object, not a pointer
to the original object itself is passed.

This means that the original object is not modified, but the copy within
the function is or may be.

Try the following:

swap <- function(x, y)
{ 
  x.save <- x
  x <- y
  y <- x.save
  sprintf("x = %d, y = %d", x, y)
}


> x <- 1
> y <- 2

> swap(x, y)
[1] "x = 2, y = 1"

> x
[1] 1
> y
[1] 2


The original x and y values are unchanged, even though they were swapped
within the function.

Now, I could re-write the swap() function to something like the
following using "<<-":

swap <- function(x, y)
{ 
  x.save <- x
  x <<- y
  y <<- x.save
  sprintf("x = %d, y = %d", x, y)
}

and end up with:

> x
[1] 1
> y
[1] 2

> swap(x, y)
[1] "x = 1, y = 2"

> x
[1] 2
> y
[1] 1

Here we get the opposite behavior, where the local copies of x and y in
the function are unchanged, but the original values are.

One could also use something like eval.parent() to play around with this
behavior as well, which I just noted that Gabor has pointed out in his
reply.

HTH,

Marc Schwartz


On Sun, 2005-11-06 at 17:48 +0000, Adaikalavan Ramasamy wrote:
> I do not understand what your question is. Can you clarify with an
> example or analogies to other programming language.
> 
>  my.fun <- function(x, y=1){ x^y }
> 
>  my.fun(5)        # returns 5 
>  my.fun(5, 2)     # returns 25
>  my.fun(y=2, x=5) # returns 25
> 
> Regards, Adai
> 
> 
> On Sun, 2005-11-06 at 03:28 +0000, Xiaofan Li wrote:
> > Hello guys,
> > 
> > I am wondering the default way of transferring arguments in R. Is it by
> > value or by ref in default case, or could that be changed explicitly?
> > 
> > Cheers,
> > Xiaofan




More information about the R-help mailing list