[R] does save.image() also save the random state?
Duncan Murdoch
murdoch.duncan at gmail.com
Fri Feb 5 18:25:32 CET 2016
On 05/02/2016 11:49 AM, Dénes Tóth wrote:
> On 02/05/2016 05:25 PM, Duncan Murdoch wrote:
> > On 05/02/2016 11:14 AM, Jinsong Zhao wrote:
> >> Dear there,
> >>
> >> Here is a snipped code,
> >>
> >> > rm(list = ls())
> >> > x <- 123
> >> > save.image("abc.RData")
> >> > rm(list = ls())
> >> > load("abc.RData")
> >> > sample(10)
> >> [1] 3 7 4 6 10 2 5 9 8 1
> >> > rm(list = ls())
> >> > load("abc.RData")
> >> > sample(10)
> >> [1] 3 7 4 6 10 2 5 9 8 1
> >>
> >> you will see that, after loading a abc.RData file that is saved by
> >> save.image(), sample(10) gives the same results. I am wondering whether
> >> it's designed purposely. And if it is, how can I get a different results
> >> of sample(10) every time after loading the saved image?
> >
> > This happens because you are reloading the random number seed. You can
> > tell R to ignore it by calling
> >
> > set.seed(NULL)
> >
> > just after you load the image. See ?set.seed for more details.
> >
> > Duncan Murdoch
> >
>
> Based on your problem description, it seems that you actually do not
> want to restore the whole workspace but only the objects that you worked
> with. If this is indeed the case, it is much better to use
> save(list=ls(), file = "abc.RData") instead of save.image("abc.RData").
> (Actually it is almost always better to use an explicitly parametrized
> save() call instead of save.image()).
>
> save.image() can cause a lot of troubles besides the one you faced
> recently (which is caused due to the save and restore of the
> .Random.seed hidden object, as Duncan mentioned).
Yes, that's good advice.
One problem I've heard of is that some people save the workspace a few
times before reading that it's good to tell R not to save on exit. Then
they keep reloading the same random seed in every session thereafter.
Duncan Murdoch
More information about the R-help
mailing list