[R] Summary: do.call and environments

Gabor Grothendieck ggrothendieck at myway.com
Thu Mar 11 10:03:23 CET 2004



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*.

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.




More information about the R-help mailing list