From khansen at stat.Berkeley.EDU  Wed Feb 13 19:44:02 2008
From: khansen at stat.Berkeley.EDU (Kasper Daniel Hansen)
Date: Wed, 13 Feb 2008 10:44:02 -0800
Subject: [Rd] Best way to reset random seed when using set.seed() in a
	function?
In-Reply-To: <59d7961d0802130857l7b4abcfcu891c066bcbe3d21a@mail.gmail.com>
References: <59d7961d0802130857l7b4abcfcu891c066bcbe3d21a@mail.gmail.com>
Message-ID: <86164ACE-3AA1-4DE7-AF6A-DA6A25186E6B@stat.berkeley.edu>

When is this really necessary? I have seen functions that do this, I  
have never seen any usage where I think it is necessary. Usually it  
is because the functions do say mcmc or cross-validation and wants  
repeatable behaviour. But if the user really wants that, he/she can  
just do it outside the functions. On the other hand, if functions  
play with the random generator they are in peril or destroying a  
possible outer loop which also uses random numbers.

Kasper

On Feb 13, 2008, at 8:57 AM, Henrik Bengtsson wrote:

> Hi,
>
> this is related to a question just raised on Bioconductor where one
> function sets the random seed internally but never resets it, which
> results in enforced down streams random samples being deterministic.
>
> What is the best way to reset the random seed when you use set.seed()
> within a function?  Is it still to re-assign '.Random.seed' in the
> global environment as following example illustrates?  I'm not too kind
> of having function modifying the global environment, if not really
> necessary.
>
> foo <- function(n) {
>   # Pop random seed
>   if (!exists(".Random.seed", mode="numeric"))
>     sample(NA);
>   oldSeed <- .Random.seed;
>
>   # Fixed seed to get reproducible samples here
>   set.seed(0xbeef);
>   x <- sample(5);
>
>   # Proof of concept: 'x' should be the same all the time
>   stopifnot(identical( x, as.integer(c(4,2,5,1,3)) ));
>
>   # Push random seed to old state
>   assign(".Random.seed", oldSeed, envir=globalenv())
>
>   # Continue as nothing happened
>   sample(n);
> }
>
>> foo(5)
> [1] 4 2 3 5 1
>> foo(5)
> [1] 4 2 3 1 5
>> foo(5)
> [1] 5 3 1 4 2
>> foo(5)
> [1] 5 3 2 4 1
>> foo(5)
>
> Is this the way to do it?
>
> Thanks
>
> Henrik
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] Best way to reset random seed when using set.seed() in a function?
Kasper Daniel Hansen