[R] saving variables created by functions in the workspace

Gabor Grothendieck ggrothendieck at myway.com
Sat Feb 21 14:47:54 CET 2004

sinx is local to your function so it is only known within
the function, not outside it.  The reason its like that is
to promote modularity.

You can do one of the following:

1. Return it explicitly from your function:
       plotsinx <- function(x) { sinx <- sin(x); plot(sinx); sinx }
Now call it like this:
       sinx <- plotsinx(x) 

2. Use assign and explicitly assign it in the global   
environment rather than the local environment of the function:       
   plotsinx <- function(x) { 
See ?assign

3. Use <<- as in:
   plotsinx <- function(x) { 
       sinx <- sin(x)
If you use this one be sure that you don't nest the 
definition of plotsinx in another function since it actually
searches through the environments of the definition's
parents.  See ?"<<-"

If you just want to look at it but not manipulate it outside
of the function you could try these:

4. Use print.   See ?print

   plotsinx <- function(x) { 
       sinx <- sin(x)

5. Use debug
   Now when you run the function you can step through it line
   by line displaying each of the local variables if you like.
   See ?debug

Date:   Sat, 21 Feb 2004 11:07:00 +0100 (CET) 
From:   =?iso-8859-1?q?Fulvio=20Copex?= <copellifulvio at yahoo.it>
To:   <r-help at stat.math.ethz.ch> 
Subject:   [R] saving variables created by functions in the workspace  

Hello ,

just a simple question from a beginner:

I write the function:
plotsinx <- function()
I recall it:
and the plot works properly.
but then in the workspace if I want to look at the
values of sinx the following error is displayed:
Error: Object "sinx" not found.
How to save the variables created by the function on
the workspace?
Thank you very much, it seems to be very trivial...

More information about the R-help mailing list