setting seed locally (not globally) in R
Something like this does it for me:
myfunction <- function () {
old <- .Random.seed
set.seed(2)
res <- runif(1)
.Random.seed <<- old
res
}
Or perhaps more elegantly:
myfunction <- function () {
old <- .Random.seed
on.exit( { .Random.seed <<- old } )
set.seed(2)
runif(1)
}
For example:
> myfunction()
[1] 0.1848823
> runif(1)
[1] 0.3472722
> myfunction()
[1] 0.1848823
> runif(1)
[1] 0.4887732