[R] Summary: do.call and environments
Liaw, Andy
andy_liaw at merck.com
Thu Mar 11 15:00:53 CET 2004
Gabor,
> From: Gabor Grothendieck
>
> Note that R and S are fundamentally different when it comes to
> scoping.
>
> R uses lexical scoping, i.e. the parent environment of a function
> is the environment at the point where it is *defined* whereas
> S uses dynamic scoping, i.e. the parent environment in a function
> is the environment at the point where the function is *called*.
I don't think that's quite right. S does not use dynamic scope. This
simple example fails in S-PLUS (6.1):
> g <- function() x + y
> f <- function() {
+ x <- 2
+ y <- 3
+ g()
+ }
> f()
Problem in g(): Object "y" not found
Use traceback() to see the call stack
It would have worked if S has dynamic scope: variables defined in the
caller's (f in this case) frame is visible to the function being called (g
in this case). The S scoping rule is described in the S-PLUS programmer's
guide, as well as V&R's `S Programming' (which also describes R's lexical
scope).
And of course, the example doesn't work in R, either:
> g <- function() x + y
> f <- function() {
+ x <- 3
+ y <- 2
+ g()
+ }
> f()
Error in g() : Object "x" not found
Cheers,
Andy
> Thus, anything regarding scoping will be different in the
> two systems.
>
> Note that in S, the question is easy since all you need is:
>
> x <- 7
> fx <- function(y) print(x*y)
> f <- function(fx, x) do.call(fx,list(3))
> f("fx",2)
>
> This gives 6 in S but 21 in R. (Better check this since I
> don't have access to S and am going by my understanding.)
>
> In fact, this entire exercise can be regarded as simulating
> S-style dynamic scoping in R.
>
> ---
> Date: Thu, 11 Mar 2004 09:45:32 +0100
> From: Thomas Petzoldt <petzoldt at rcs.urz.tu-dresden.de>
> To: Spencer Graves <spencer.graves at pdf.com>
> Cc: <ggrothendieck at myway.com>, <r-help at stat.math.ethz.ch>
> Subject: Re: [R] Summary: do.call and environments
>
>
> Hello,
>
> > > f("fx",2)
> > [1] 6
> >
> > I would have naively expected 14. From whence cometh "6"?
> > Also, I prefer to use transportable code wherever feasible. The
>
> 2*3=6, which was the intention. It is in fact only a proof of
> correctness, that "7" is not used here. The proposal of Gabor does
> exactly, what I want, but if it does not work on S-PLUS, it's
> a serious
> disadvantage and I should check this too.
>
> Thomas P.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
>
------------------------------------------------------------------------------
Notice: This e-mail message, together with any attachments,...{{dropped}}
More information about the R-help
mailing list