[R] variable scope
Bill.Venables@cmis.csiro.au
Bill.Venables at cmis.csiro.au
Sat Aug 3 06:35:03 CEST 2002
Passing variables to functions "by reference" is possible, if you must, but
not recommended. Some functions already do this, for example
fix(myfunc)
will alter the value of `myfunc' in the present environment.
If you can stand a piece of admittedly avuncular advice, I'd say look again
at your problem and see if you really do want to do this. With a
programming language it is usually the case that you are better off
understanding and working within its logic and philosophy rather than trying
to make it behave in a way that you think it should.
If you still want to go through with this, you might want to look at Thomas
Lumley's article on Macros in the Programmer's Niche section of R-news a
couple of issues ago. Using call by reference is very similar to using
macros instead of true functions. I personally think it is both dangerous
and unnecessary, but Thomas points out that if you must it can be done
reasonably elegantly.
Sigh.
Bill Venables.
> -----Original Message-----
> From: VBMorozov at lbl.gov [mailto:VBMorozov at lbl.gov]
> Sent: Saturday, August 03, 2002 12:39 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] variable scope
>
> Dear R-guRus:
>
> I would like to pass variables to a function in R in "by reference",
> e.g Fortran style.
> For example, suppose I have the following code
>
> x<-c(1:10)
> y<-1
> MyFunc<-function(x,y) {y<-sum(x); return(NULL)}
> MyFunc(x,y)
> print(y)
>
> in this case print(y) will produce "1" instead of 55 (which is sum(x)) -
> how do I make sure that afte the function is run, y remembers the
> value that was given to it within a function ????
>
> Of course I could always do something like
>
> MyFunc<-fuction(x) {return(sum(x)}; y<-MyFunc(x)
>
> but in the real life I have a much more complex problem so I really
> would like to be able to pass variables to functions by reference.
>
> Thank you very much,
> Vladimir
>
>
>
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
> -.-.-
> r-help mailing list -- Read
> http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._.
> _._._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list