[R] Variable modified from within a function

From: Josselin Noirel <mailing_at_jnoirel.fr>
Date: Fri, 29 Feb 2008 13:21:54 +0100

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

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Fri 29 Feb 2008 - 13:10:37 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 29 Feb 2008 - 13:30:17 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive