[R] Communicating from one function to another
Thomas L Jones, PhD
jones3745 at verizon.net
Mon Nov 26 18:11:14 CET 2007
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.
Question 1: Is this practical at all in the R language?
Suppose the variable is called x23. I want to assign a value to it, then use
it later. Seemingly, there are two cases:
Case I is if the variable is given its value at the top level.
Case II is if it is given its value inside a user-defined function. That I
do not know how to do.
Example:
func1 <- function (){
x23 <- 2.6
return ()
}
driver_func <- function (){
func1 ()
print (x23)
return ()
}
However, when I call driver_func, it won't work. Beginning with the load
operation, I get:
----------------------------------------------------------------
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> func1 <- function (){
+
+ x23 <- 2.6
+
+ return ()
+
+ }
>
> driver_func <- function (){
+
+ func1 ()
+
+ print (x23)
+
+ return ()
+
+ }
> driver_func ()
Error in print(x23) : object "x23" not found
>
---------------------------------------------------------------------------
>From Tom:
Clearly, the two functions cannot communicate. I am aware of the existence
of environments, but don't know much about them. Also, the attach function
and the get and set functions. Also, .GlobalEnv It might or might not make
sense to create a list of "all" of the variables, with two functions which
get all of them and set all of them. The function calls may be thought of as
an upside down tree. I want to be able to communicate from any node to any
other node.
Your advice?
Tom
Thomas L. Jones, PhD, Computer Science
More information about the R-help
mailing list