[R] global variable

Martyn Plummer plummer at iarc.fr
Fri Jan 7 17:22:56 CET 2000


Variables in the global environment are visible from within all functions
(unless masked by a local variable of the same name).

> x <- 1:3
> foo <- function() {print(x)}
> foo()
[1] 1 2 3

You can write to the global environment from within a function using
the operator "<<-". Here for example x is written to the global
environment in foo() and read in bar() without being passed as an argument.

> bar <- function() {x <<- 1:5}
> bar()
> foo()
[1] 1 2 3 4 5

However, S is a functional language and this sort of thing is considered
bad form (I should also say that the behaviour of "<<-" is slightly more
complicated than this, see help("<<-")).

You can also use lexical scoping. In R, a function has access to the
variables in the environment in which it was defined:

baz <- function() {
   foo <- function() {print(x)}
   x <- 1:3
   foo()
}
> baz()
[1] 1 2 3

This won't work in S.

Martyn

On 07-Jan-00 Christine Serres wrote:
> Hi,
> 
> I would like to know if it is possible to make global variables in R.
> My problem is that I use the same data frame in many different functions
> that I have written, but it implies a very big waste of time because it
> slow down the program.
> So I would use my data frame without need to copy it each time in
> another function to have a faster program execution.
> How can I do ??
> 
> Thanks for Help
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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