[R] Communicating from one function to another

Duncan Murdoch murdoch at stats.uwo.ca
Mon Nov 26 19:38:03 CET 2007


On 11/26/2007 1:25 PM, Alberto Monteiro wrote:
> Thomas L Jones wrote:
>>
>> My question is a seemingly simple one. I have a bunch of user-
>> defined functions which compute such-and-such objects. I want to be 
>> able to define a variable in a particular function, then make use of 
>> it later, perhaps in a different function, without necessarily 
>> having to move it around in argument lists. In the C community, it 
>> would be called a "global" variable.
>> 
> Global variables in R are used with <<- instead of <-.
> 
> For example:
> 
> x <- 1
> y <- 1
> 
> f <- function() {
>    x <- 2
>    y <<- 2
> }
> 
> f()
> 
> will turn y to 2 but will not change x.
> 

R doesn't really have global variables.  <<- goes looking in parent 
environments until it finds the target variable, and makes the 
assignment there.  If it never finds one, it makes the assignment in the 
"global environment", but the name is misleading:  it should really be 
called the "user workspace".

Duncan Murdoch



More information about the R-help mailing list