[R] Question on closure (lexical scoping) and encapsulation

Duncan Murdoch murdoch at stats.uwo.ca
Wed Jun 14 16:00:45 CEST 2000

On Tue, 13 Jun 2000 15:47:18 -0400, you wrote in message
<39468FC6.B041ED26 at acsu.buffalo.edu>:

>Dear R users,
>I have two related questions about scoping and data encapsulation.
>One is fairly specific - I am looking at "scoping.R" which is used in
>demo(scoping) - it's an example of lexical scoping and encapsulation.
>Where is the 'total' stored? It is not an attribute in 'ross' or
>however, functions like balance() have access to it.
>Is it more or less like a private class member in C++, so that it's not
>possible to access it from outside of class? Or is it possible to access
>in some way?

Others have explained that total is in an environment.  Environments
are somewhat like instances of classes in C++:  they have inheritance
(since they have parent environments), they can hold functions and
data.  There's no concept of "private" vs. "public":  all objects in
an environment are visible to any code.  There's also no concept of a
class type:  each environment is unique, with no way to specify that
two environments contain the same members.  

It's also rather cumbersome to extract a member from an environment,
you need the "get" function. It would probably make sense to overload
$ to work on environments, so that instead of Doug Bates' code

  get("total", env = environment(ross$balance))

you could just type


Print methods for environments would be nice; these should do an ls()
of the environment and say what the parent environment is.

It would also probably make sense to base the object oriented aspects
of S on environments rather than on naming conventions and attributes,
but it's probably too late to do that now.

Duncan Murdoch
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