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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to