[R] Variable modified from within a function

Josselin Noirel mailing at jnoirel.fr
Fri Feb 29 13:21:54 CET 2008


Dear all,

I quickly checked on the internet and nothing relevant came up, so, I
hope to find the answer to a question here.  I'd pleased to be
redirected towards relevant pieces of information on the internet, if I
merely missed something obvious.

Actually, I've got two somewhat related questions.  The first one is
about accessing a variable from the caller function.  Owing to the
differences in the scoping rules in S+ and R, it is not (at least
directly) possible to access f()'s variable "data" from g() in the
following example:

f <- function (...) {
  data <- my.readfile(...);
  g(...)
}

g <- function (...) {
  # Do something with data?
}

The thing is that passing "data" as an argument to g() involves copying
the data, if I understood correctly.  Something I'd be keen to avoid
because in the real programme I want to write, g() is called many a time
and data is rather big (not infamously massive, though, something like a
500x20 matrix).  If no other solution exists, I can do this:

f <- function (...) {
  data <- my.readfile(...);
  g <- function (...) {
    # Do something with data
  }
  g(...)
}

This may be very common practice in R, I don't know, but my feeling as a
beginner is that it's rather inelegant, especially if you need define
many such functions.  So my first question is: is there another way of
sharing a variable across functions or should I consider that the
elegance isn't an issue?

The second question relates to modifying a variable from within a
function.  In the real code, this applies to another variable, but let's
suppose that within g(), I'd like to modify data[index] for a given
index.  Apparently, data[index] <- new.value makes data become a local
variable of g and any modification remains unnoticed by f() and other
functions.  So, is there any convenient to do that without returning big
arrays, vectors, or whatever?

Many thanks in advance.

-- 
Joss



More information about the R-help mailing list