[R] changing function argument

Thomas Lumley tlumley at u.washington.edu
Fri Mar 13 10:21:25 CET 2009


On Fri, 13 Mar 2009, Thomas Mang wrote:

> Hi,
>
> 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)
>

It's possible in your example

test<-function(x){
    eval(substitute(x<-10),parent.frame())
    return(42)
}

However, it is still likely to be a bad idea.  What do you want to happen for
  test(5)
  test(x+y)
  test(test(y))

  retest<-function(z) {z<-5; test(z); print(z)}
  retest(x)


R really doesn't have pointer or reference types, and there's no way to ensure that the arguments to a function are lvalues.


      -thomas

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle




More information about the R-help mailing list