[R] R newbie...

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Tue Dec 6 19:25:55 CET 2005

On 06-Dec-05 David Hajage wrote:
> Hello,
> I'm a new user...
> I have a function :
> calculate <- function(x,y)
>   {
>      z <- x + y
>   }
> I would like to use the result (z) with another function :
> recalculate <- function(...)
>   {
>      a <- z^2
>   }
> But R says that z does not exist...
> How can I use z in an another function ?
> Thank you for your answer...

With 'calculate' as written, z is "internal" to 'calculate'
and is not visible from outside (and the internal assignment
to z will not affact the value of a variable also called z
outside the function). The simplest way to extract the
calculated value is to "return" it from the function and
assign it to z outside the function:

  calculate <- function(x,y)
       return(x + y)


and then say


where, again, you need to "get a out of" the function, so

  recalculate <- function(...)

While it is possible to change the values of "external"
variables from within functions, this is not a recommended
way to proceed, since it depends on the named variable
inside the function meaning the same as the variable with
the same name outside the function. Since the purpose of
defining functions is to have something which is re-usable
in different contexts, it is generally desriable to make
function definitions independent of the environment from
which they may be called.

Hoping this helps,

E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 06-Dec-05                                       Time: 18:25:53
------------------------------ XFMail ------------------------------

More information about the R-help mailing list