[R] variables

Jason Turner jasont at indigoindustrial.co.nz
Wed Oct 1 00:04:23 CEST 2003


forkusam wrote:
> Hi,
> can someone please help me.
> I will give a simple example of my problem. 
> p <- function()
> {
>  i <- 1
>  sr <- function(){
>  i<-i+3
>  i<- sqrt(i)
> }
> cat(i) 
> }
>  This is just an example. My main problem is defining
> i like a global variable which I can use in the sub-
> and main functions without any complicated switches. 
> Thanks in advance.
> cilver

Within the function p(), it should "just work".  Try this slight 
variation of your example:

p <- function()
{
   i <- 1
   sr <- function(){
     i<-i+3
     i<- sqrt(i)
     i #explicitly return the newly calculated value
   }
   cat("sr() returned ",sr(),"\n")
   #now check if i was actually modified outside sr()
   cat("i = ",i,"\n")

}

When I load this into R...

 > p()
sr() returned  2
i =  1

note that i is not visible outside the function p().  It disappears when 
p() exits.

 > i
Error: Object "i" not found

The internal function variables being available to sub-fuctions is an 
example of "lexical scoping", and it's one of the things that makes R so 
nice to work with.  Try demo(scoping) for a very interesting use of 
lexical scoping.

Cheers

Jason

-- 
Indigo Industrial Controls Ltd.
http://www.indigoindustrial.co.nz
64-21-343-545
jasont at indigoindustrial.co.nz




More information about the R-help mailing list