R-beta: Re: S Compatibility

Kurt Hornik Kurt.Hornik at ci.tuwien.ac.at
Wed Apr 30 10:23:14 CEST 1997


>>>>> Bill Venables writes:

> Ross Ihaka writes:
>> Bill Venables writes:
>> 
>> > Are the scoping differences between R and S set out precisely and
>> > definitively somewhere?  This would be useful.
>> 
>> In the source code perhaps? :-)

> I should have added `concisely' ...

>> You can find a pretty precise description in the article Robert and I
>> did in JCGS.  

> May I suggest the reference be added to the FAQ if it is not
> already there?  It may not actually be a frequently asked
> question, but it should be.

Actually, the FAQ spends quite some time on this issue:

  Whereas the developers of R have tried to stick to the S language as
  defined in ``The New S Language'' (Blue Book, see question ``What is
  S?''), they have adopted the evaluation model of Scheme.

  This difference becomes manifest when free variables occur in a
  function.  Free variables are those which are neither formal
  parameters (occurring in the argument list of the function) nor local
  variables (created by assigning to them in the body of the function).
  Whereas S (like C) by default uses static scoping, R (like Scheme) has
  adopted lexical scoping.  This means the values of free variables are
  determined by a set of global variables in S, but in R by the bindings
  that were in effect at the time the function was created.

  Consider the following function:

       cube <- function(n) {
         sq <- function() n * n
         n * sq()
       }

  Under S, sq() does not ``know'' about the variable n unless it is
  defined globally:

       S> cube(2)
       Error in sq():  Object "n" not found
       Dumped
       S> n <- 3
       S> cube(2)
       [1] 18

  In R, the ``environment'' created when cube() was invoked is also
  looked in:

       R> cube(2)
       [1] 8

  Lexical scoping allows using function closures and maintaining local
  state.  A simple example (taken from Abelson and Sussman) can be found
  in the `demos/language' subdirectory of the R distribution.  Further
  information is provided in the standard R reference ``R: A Language
  for Data Analysis and Graphics'' (see question ``Which Documentation
  Exists for R?'') and a paper on ``Lexical Scope and Statistical
  Computing'' by Robert Gentleman and Ross Ihaka which can be obtained
  from the `doc/misc' directory of a CRAN site.

-k
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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