[R]: global and local variables

Karl Knoblick karlknoblich at yahoo.de
Tue Dec 9 20:14:37 CET 2003


Hi!

I'm no guru in R. But I can think of 2 ways (have to
be tried):

1) As Uwe Ligges said: just save return the stored
variable a<-preprocess(xdata) and return it (if you
want to return more than 1 item use list) and give
this variable to the next function. Example:

func1<-function(x) 
{
y<-x^2
# for testing:
print(paste("func1", x, y))
return(y) 
}

func2<-function(x, valuefunc1=NA)
{
if (is.na(valuefunc1)) valuefunc1<-func1(x)
# calculate things with valuefunc1
print(paste("func2", x, valuefunc1))
return(list(valuefunc1=valuefunc1))
}

func3<-function(x, valuefunc1=NA)
{
if (is.na(valuefunc1)) valuefunc1<-func1(x)
# calculate things with valuefunc1
print(paste("func3", x, valuefunc1))
return(list(valuefunc1=valuefunc1))
}

# use this
a<-list(NA)
names(a)<-c("valuefunc1")

a<-func2(x=3, valuefunc1=a$valuefunc1)
a<-func3(x=3, valuefunc1=a$valuefunc1) # be careful,
makes only sense if the x is equal to former fuction
call...
a<-func3(x=999, valuefunc1=a$valuefunc1) # will be the
same
a<-func3(x=999) # will be different 


2) use global variables like
assign("stored.value", x, envir=.GlobalEnv)
example see reply of my posting:
RE: [R] LOCF - Last Observation Carried Forward Simon
Fear (Sat 15 Nov 2003 - 03:28:03 EST) 

HTH,
Karl




More information about the R-help mailing list