[R] (structured) programming style

Ross Boylan ross at biostat.ucsf.edu
Fri Sep 12 01:33:53 CEST 2003

I find that because R functions are call by value, and because there are
no pointer or reference types (a la C++), I am making fairly heavy use
of lexical scoping to modify variables.  E.g.
outer <- function() {
  m <- matrix(0, 2, 2)
  inner <- function() {
    m[2,2] <<- 3

I am not too pleased with this, as it violates basic rules of structured
programming, namely that it is not obvious what variables inner is
reading or writing.  It's not as totally out of control as the use of
global variables, but it's still bothersome.  In practice, I have many
variables and several levels of nesting that come into play.

A slightly subtler problem is that some of the variables in outer are
just for use by outer, while others are used for communication down the
line.  One can't tell by quick inspection what's what.

I am trying to compensate by commenting the code heavily, but I'd rather
not use a style that makes that necessary.

I recognize that I could pass m as an argument to inner and return a
modified version of it.  Assuming more than one variable was involved
(as would usually be the case) I'd need to put the "new" m in a list
returned from inner, and then unpack the list in the outer function. 
This is not only rather ugly, but I imagine it also raises some
performance issues.

All of which has me wondering if there are some more natural ways to use
the language to the same general ends.  Can anyone comment?

Ross Boylan                                      wk:  (415) 502-4031
530 Parnassus Avenue (Library) rm 115-4          ross at biostat.ucsf.edu
Dept of Epidemiology and Biostatistics           fax: (415) 476-9856
University of California, San Francisco
San Francisco, CA 94143-0840                     hm:  (415) 550-1062

More information about the R-help mailing list