[R] Communicating from one function to another

Gabor Grothendieck ggrothendieck at gmail.com
Tue Nov 27 05:45:11 CET 2007


Others have already answered your direct question but consider that
what you may want without realizing it is object-oriented programming.

Here p is a proto object with components x and f.  x is a variable and f is a
method. The method f sets x to a.  (Presumably in reality f would do other
things too but for this example that's all it does.)   Before invoking
f, x is 0
and after invoking f x is 3.  Lastly we invoke method g on proto object p and
get back 30.

library(proto)
p <- proto(x = 0, f = function(., a) .$x <- a, g = function(.) .$x * 10)
p$x  # 0
p$f(3)
p$x # 3
p$g() # 30

See:
   http:/r-proto.googlecode.com
for more.

On Nov 26, 2007 12:11 PM, Thomas L Jones, PhD <jones3745 at verizon.net> 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.
>
> 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