[R] use "save.image" inside a function?

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Jan 9 17:43:32 CET 2008


save.image() saves the global workspace: it does not save the environments 
of executing functions.  If you want to save the latter, use the 'envir' 
argument of save().

On Tue, 8 Jan 2008, Hua Li wrote:

> Hi, All
>
> I'm trying to save the workspace as a Check Point for
> possible future come back. The "save.image" function
> works if the whole coding is in a main function:
>
> rm(list=ls())
> t = 1
> t = t+1
> print(paste("before",t))
> # [1] "before 2"
> save.image("tt.RData")
>
> t = t+1
> print(paste("after",t))
> # [1] "after 3"
>
> load("tt.RData")
> print(paste("check",t))
> # [1] "check 2"
>
> As you can see, the value right before I save the
> workspace is restored.
>
> However, if I run the saving inside a function, it
> seems that it restores to the vale outside the
> function rather than the one before the save command:
>
> rm(list=ls())
> test.fcn <- function(t=1){
>         t = t+1
>         print(paste("before",t))
>         save.image("tt.RData")
>
>         t = t+1
>         print(paste("after",t))
>
>         load("tt.RData")
>         print(paste("check",t))
>
> }
>
> t = 1
> test.fcn(t=t)
> # [1] "before 2"
> # [1] "after 3"
> # [1] "check 1"
>
> So it restores the value before the program enters the
> function (t=1), though what I really want is the value
> inside the function(t=2).
>
> Is there anything wrong with the way I use the
> "save.image" function? Or is there other command I can
> use to reach my goal?
>
> Thanks a lot!
>
> Hua
>
>
>
>      ____________________________________________________________________________________
> Never miss a thing.  Make Yahoo your home page.
>
> ______________________________________________
> R-help at 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.
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list