Skip to content

variable scope

2 messages · Bill Venables, Peter Dalgaard

#
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.
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
Bill.Venables at cmis.csiro.au writes:
On the other hand, it is part of the language design to make these
things possible if you must have them. And there are a few places
where things must be by reference (actually, they are "by name", I
believe) in order to keep the "everything is done with functions"
paradigm. The "<-" function is one obvious example. And of course the
access to unevaluated expressions is utilized all over, for plot
labels and in the update() mechanisms, etc.

However, Bill's point is valid. There are several places where
these facilities have been used and later regretted by the designers.

This happens especially where we attempt to be user-friendly and allow
syntax that is not really consistent with the semantics. Notice for
instance the inconsistency between help(lm) and apropos("lm") and the
non-functioning of myhelp<-function(foo){help(foo)}. The help is not a
property of the object, but of the name of the object.

Another example that has come back to haunt us several times is
lm(...,data=d,offset=foo). The problem is that we want "foo" to be
found inside "d" if present, but call-by-value semantics imply that it
is an object in the caller's scope. You really ought to pass the name
"foo" (or maybe better: quote(foo), or a formula ~foo).

Also, it is tricky to get things exactly right, for example you can
not just fix(myfamily$linkfun).